DannyD
DannyD

Reputation: 2881

How can I order a list of lists of lists in C#

I'm actually using a list which contains lists which contains lists (yes three sets):

List<List<List<int>>> threeD = new List<List<List<int>>>();

after I fill this monster, I get this:

var threeD = [ [[18,100],[13,95]], [[12,100],[2,5],[7,45]], [[19,100]] ];

The above list contains three separate lists with a list with an x and y int. How can I sort these based on the first number. My output I would need would be this:

var threeD = [ [[13,95],[18,100]], [[2,5],[7,45],[12,100]], [[19,100]] ];

I was thinking of maybe sorting using some kind of linq statement. Or should I maybe proceed by creating nested for loops?

Edit: I only need to sort the inner-most lists and not the outer lists. They are actually cordinates for a line graph with multiple lines using jqplot so the order that each line is rendered doesn't really matter. Thanks

Upvotes: 0

Views: 668

Answers (1)

poke
poke

Reputation: 387617

You first sort the inner list of x/y numbers, and then you order the outer list:

threeD.Select(sublist => sublist.OrderBy(xy => xy[0]).ToList())
      .OrderBy(sublist => sublist[0][0])
      .ToList();

And if you just need to sort the inner list, just leave the outer sort out:

threeD.Select(sublist => sublist.OrderBy(xy => xy[0]).ToList()).ToList();

Upvotes: 3

Related Questions