views:

225

answers:

2

Hi,

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 :)

+5  A: 

Nearly a duplicate of:

http://stackoverflow.com/questions/721577/how-to-sort-listliststring-according-to-liststring-number-of-fields

Something like:

var sorted = parent.OrderBy( l => l[0] );

Or:

parent.Sort( (a,b) => a[0].CompareTo( b[0] ) )
John Gietzen
yes, nearly, but I'm learning the stuff and need it also now, so I'm really sorry I'm making ALMOST duplicates, but I don't think it's a bad idea.. Thank you
Skuta
This error pops at "parent.sort" -> Error 1 Identifier expected
Skuta
the first example's doing the same. Identifier expected. at [0]
Skuta
The dot after 'l' is wrong - should read just 'l[0]' instead of 'l.[0]'.
Daniel Brückner
Oops, fixed. I feel dumb now.I guess that's what I get for not testing code.
John Gietzen
it's ok I found it straightaway :)
Skuta
Hi, any reason this wouldn't work?: temp.Sort((a, b) => a[1].CompareTo(b[1])); it says that it's out of index but it is not, I check it with IF statement befoer..
Skuta
+3  A: 

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());
Samuel
+1, Should I include this in my answer?
John Gietzen
If you wish, but both answers are short enough to be seen if they look.
Samuel
May be it should even be FirstOrDefault() to avoid a exception in case of an empty sub item.
Daniel Brückner
You could, but with .First() and an empty sub list, the sequence returned will be empty.
Samuel