2

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.

0

3 Answers 3

7
var foos = new List<Foo>(); 
// consider this is your class with the integer variable called layer

var ordered = foos.OrderBy(f => f.layer);

Enumerable.OrderBy

Sign up to request clarification or add additional context in comments.

4 Comments

entities = entities.OrderBy(f => f.layer).ToList<Entity>(); Should this work? i'm using it but the results im getting are just in the order i added them still.
@ben657: ToList() creates a new List based on the new order but it does not modify the old List<Entity>.
But i'm assigning it there aren't I? whether i'm way off in my thinking, or i'm assigning the new ordered list to the old one?
@ben657: Yes, that should work as you see in this simplified example: List<int> list = new List<int>() { 2, 3, 1 }; list = list.OrderBy(i => i).ToList();
1

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().

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.