Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List.OrderBy with multiple lists

Tags:

c#

list

linq

I got 5 lists. One is containing the date of release and the others are the attributes of that list but seperated in multiple lists.

List<string> sortedDateList = x1.OrderBy(x => x).ToList();

This code is sorting the list with the oldest date first, like it should. But I also want to sort (sync) the other attributes list, because they need the same index as the date.

How can I realize that? I'm new to Linq-methods.

like image 275
TNation Avatar asked May 17 '26 16:05

TNation


1 Answers

You could use the .Zip() method to combine the lists as described here. You could combine them into a class or an anonymous type and then sort them.

int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };

var numbersAndWords = numbers.Zip(words, (first, second) => new { Num = first, Word = second });

var sorted = numbersAndWords.OrderBy(x => x.Num).ToList();

Alternately, if you can guarantee that all the lists are of the same length (or just grab the shortest list) you could use the following instead of the .Zip() extension.

var numbersAndWords = numbers.Select((number, i) => new { Num = number, Word = words[i], Foo = myFoos[i] }); // Where myFoos is another collection.

And in the lambda combine all the items from the separate lists into an object at the same time by accessing the collection by index. (Avoids multiple use of .Zip()) Of course, if you try to access an index that is larger than the list size you will get an IndexOutOfRangeException.

like image 118
Simon Avatar answered May 19 '26 06:05

Simon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!