Reputation: 3853
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.
Upvotes: 2
Views: 17051
Reputation: 3853
After neither of these methods worked, I did a bit more research and came up with this snippet which worked for me:
entities.Sort(delegate(Entity a, Entity b) { return a.layer.CompareTo(b.layer); });
Just replace Entity with whatever object is in the list, and layer with whatever you want to sort by.
Upvotes: 0
Reputation: 2231
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().
Upvotes: 1
Reputation: 460098
var foos = new List<Foo>();
// consider this is your class with the integer variable called layer
var ordered = foos.OrderBy(f => f.layer);
Upvotes: 6