Doing a college project and I\'m a bit stuck..
Basically, I need to take the string input for an employee name and an integer input for the amount of properties they sol
I have stored the name and properties sold in their own separate lists, I know how to sort the number list in size order but then how do I link it back with the appropriate name?
The other answers give mostly good advice. Summing up, it is:
However it is worth pointing out that there are also methods to answer your question directly, namely, how do I sort one list by the elements of another list?
Method one
Once you have built both lists, use ToArray
on both of them. Then use the overload of Array.Sort
which takes two arrays, one of keys, and one of value, but sorts both of them by the key array:
https://docs.microsoft.com/en-us/dotnet/api/system.array.sort?view=netframework-4.8#System_Array_Sort_System_Array_System_Array_System_Int32_System_Int32_
Method two
Suppose you have elements numbered 0, 1, 2, 3 in both lists. Create that sequence of numbers:
var indices = Enumerable.Range(0, names.Length);
Now sort that sequence by the corresponding value:
var sortedIndices = indices.OrderBy(i => numbers[i]);
Make sure this step is clear. If we have numbers 40, 30, 10, 20
then we are ordering the numbers 0, 1, 2, 3 by the corresponding values in this sequence, so we will get 2, 3, 1, 0.
Now we can transform that into a sequence of names!
var sortedNames = sortedIndices.Select(i => names[i]).ToList();
Method three
Use the Zip
sequence operator to form a "zipper join". That is, join up the two sequences like the teeth meshing in a zipper. Then order the sequence of pairs by the number, and then extract the sorted sequence of names:
var sorted = names.Zip(numbers, (name, number) => (name, number))
.OrderBy(p => p.number)
.Select(p => p.name)
.ToList();
I strongly recommend that you make a study of the operations you can perform on sequences in C#. They are extremely powerful tools.