How to sort List<List<UInt32>> according to List<UInt32>[0] number ASC/DESC in C#?
Question
How shall sort this in ASC order?
I got List<List<UInt32>>
full of records of List<UInt32>
and I want those records to be sorted according to the first column in each record - the column is UInt32 number.
So:
I have List of:
new List<UInt32>: 32,1,1,1,1,1
new List<UInt32>: 22,2,2,2,2,2
new List<UInt32>: 32,1,1,1,1,1
new List<UInt32>: 1,1,1,1,1
which should be sorted to:
List<UInt32>: 1,1,1,1,1
List<UInt32>: 22,2,2,2,2,2
new List<UInt32>: 32,1,1,1,1,1
new List<UInt32>: 32,1,1,1,1,1
-> Only first number matter! others are not important for sorting. I'm lookin for ASC thing, but both would be fantastic so when I think algorithm should be changed, I'll look it up :)
Thank you for your effort to help !
@Samuel, Thank you, I'll try to implement it when I try to change the type :)
Solution
Nearly a duplicate of:
How to sort List<List<string>> according to List<string> number of fields?
Something like:
var sorted = parent.OrderBy( l => l[0] );
Or:
parent.Sort( (a,b) => a[0].CompareTo( b[0] ) )
OTHER TIPS
While John's answer works, I would suggest using First()
instead of accessing the 0 element in the list. This way it works for any IEnumerable<T>
not just IList<T>
.
var sorted = list.OrderBy(subList => subList.First());