0

I'm trying to sort the existing list which is ICollection<T> but failed. Below is what I've tried. No error but no effect as well.

....
ObjectList.OrderBy(x=>x.Name);
....

Am I totally off from sorting the list using the above way? I also tried:

ObjectList = ObjectList.OrderBy(x=>x.Name);

but this is worse as it's giving me error saying I'm missing a cast.

Is it possible to sort the same list instead of assigning it to another variable?

8
  • 1
    possible duplicate of Sorting a list using Lambda/Linq to objects
    – Sergio
    Feb 12, 2014 at 8:24
  • what type of ObjectList?
    – Grundy
    Feb 12, 2014 at 8:25
  • 1
    try ObjectList.ToList().Sort();
    – w.b
    Feb 12, 2014 at 8:26
  • you can try List.Sort
    – Grundy
    Feb 12, 2014 at 8:27
  • @user2720372: But it's a list of custom object. How to specify which field from ObjectList.ToList().Sort();? Feb 12, 2014 at 8:27

3 Answers 3

3

The short answer is no, it is not possible to sort an ICollection without assigning it to another variable. The ICollection interface does not expose any way to do that.

However sorting with OrderBy as in your example works as excpected, but returns an IEnumerable and not an ICollection.

I would assign it to another variable like so:

var sortedList = ObjectList.OrderBy(x=>x.Name);
1
  • 1
    He could also do ObjectList = ObjectList.Orderby(x => x.Name).ToList() since List<T> implements ICollection<T> but that just avoid having a different variable but still creates a new collection and doesn't sort in-place.
    – Dirk
    Feb 12, 2014 at 8:31
2

You must add .ToList() at the because OrderBy returns an IEnumerable, so you try as:

ObjectList = ObjectList.OrderBy(x=>x.Name). ToList() ;
1
  • I can't believe is that simple. Works like charm. Will accept as answer real soon Feb 12, 2014 at 8:31
1

Such a generic sort operation does not exist, because it is unclear how to sort a generic collection. If your collection was List<T>, you could use the Sort method there (because it is possible to sort a list). However, other collections like e.g. hash sets simply do not allow to be sorted, so you will have to create a new collection, if you want your collection to be sorted.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.