Jose Maria de la Torre
Jose Maria de la Torre

Reputation: 265

Sort list of list C#

I need help sorting a list of list, by an attribute in the inner list.

List<List<int>> Nota = new List<List<int>>();
Nota.Add(new List<int> { 0,1,3,4});
Nota.Add(new List<int> { 0,3,3,4});
Nota.Add(new List<int> { 0,2,3,4});

then I wish to sort by the second element in the inner list, so the result should be

{ 0,1,3,4}
{ 0,2,3,4}
{ 0,3,3,4}

after sorting..

I tried

Nota.OrderByDescending(x => - x[1]);

but had no results

thanks for the help!

Upvotes: 1

Views: 206

Answers (2)

D Stanley
D Stanley

Reputation: 152521

While not the best method, Nota.OrderByDescending(x => - x[1]); would work if you captured the output. Unlike Sort, OrderBy does not sort the list in-place, rather it returns an enumerator that will give you the items in the desired order.

So something like this would work:

Nota = Nota.OrderByDescending(x => - x[1]).ToList();

or, more simply

Nota = Nota.OrderBy(x => x[1]).ToList();

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564403

You can use List<T>.Sort:

Nota.Sort((a,b) => a[1].CompareTo(b[1]));

Upvotes: 4

Related Questions