Sort c# list of objects by variable
12,967
Solution 1
var foos = new List<Foo>();
// consider this is your class with the integer variable called layer
var ordered = foos.OrderBy(f => f.layer);
Solution 2
A couple of other ways to do it...
Assuming Layer is in scope...
List<Item> list = new List<Item>();
list.Add(new Item(10));
list.Add(new Item(2));
list.Add(new Item(5));
list.Add(new Item(18));
list.Add(new Item(1));
list.Sort((a, b) => { return a.Layer.CompareTo(b.Layer); });
Alternatively, you could implement the IComparable interface, which will allow you to sort by whatever you wanted internally in the class. Assuming the field is always what you wil want to sort by and then just call sort().
Author by
ben657
Updated on June 14, 2022Comments
-
ben657 almost 2 years
I have a class with an integer variable called "layer", there is a list of these classes, which I want to sort in ascending order. How would I go about doing this? I've tried one or two LINQ methods i've found on here, but to no avail.