OrderBy and List vs. IOrderedEnumerable

Why not just sort the list in place using the Sort() instance method; then you can add items to it later if you like:

List<string> items = GetSomeItems();
items.Sort();

Or, use an ordered collection like a binary search tree. SortedSet<T> might fit the bill, depending on your needs.

The solution suggested by the others:

items = items.OrderBy(item => item).ToList(); 

… creates another list with the original items in a new order. This is only useful if you need to preserve the original ordering for some other purpose; it’s rather more wasteful of memory than sorting the list in place.

As far as understanding the error, it’s simple: List<T> isn’t a subtype of IOrderedEnumerable<T>, so there’s no implicit reference conversion between the two. The explicit cast that the compiler suggests will satisfy the compiler, but it will fail at run time because the object returned by OrderBy<T> does not inherit from List<T>.

EDIT

An example of List<T>.Sort(Comparison<T>), assuming the type MyType has a Key property of some type type T where T : IComparable<T>:

List<MyType> items = GetSomeItems();
items.Sort((a, b) => a.Key.CompareTo(b.Key));

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)