-2

So I'm trying to sort a list of my objects using lambda like so:

List<DirectoryObjects> sort = dirObjList.OrderBy(ms => ms.name);

Visual Studio though says that is wrong and it says this is correct:

List<DirectoryObjects> sort = (List<DirectoryObjects>)dirObjList.OrderBy(ms => ms.name);

I've been exposed to lambda before but I've never really understood it. My way of doing it seems correct to me because I'm under the impression lambda is just sorting my list for me but still retaining it's type. Is it wrong to think that? The second instance looks...redundant to me. Why would I need to cast a sorted List when it already is that? Or should I think of lambdas as something that converts Enum's to a different type?

  • 1
    Does this answer your question? [OrderBy and List vs. IOrderedEnumerable](https://stackoverflow.com/questions/9285426/orderby-and-list-vs-iorderedenumerable) – devNull Nov 15 '20 at 21:24
  • `dirObjList.OrderBy(ms => ms.name).ToList()` This should nearly be closed as a typo. Maybe you should research the difference between IEnumerable and its derivatives, and List – TheGeneral Nov 15 '20 at 21:34
  • `Visual Studio though says that is wrong and it says this is correct:` To be clear, Visual Studio never says it is _correct_. It might say it _compiles_ - but it is certainly not _correct_ (for any meaningful definition of `correct`). – mjwills Nov 16 '20 at 01:16

1 Answers1

1

The lambda in itself is irrelevant here, the key is LINQ behavior.

The OrderBy extension method does NOT order your list as you think. Instead, it creates a new, independent IEnumerable<T> with the result of the sorting, leaving the original untouched. So it's not a List<T>, but a completely different type, whose only capability is to be enumerated, following the order you asked for.

A List is that and also a couple more things (irrelevant for now), but the important thing is that the return value of OrderBy is not a list. The proposed cast is also wrong just because of that, as you're trying to cast an IEnumerable<T> to List<T>. In general, those casts may or may not work, depending on the real underling type (as IEnumerable<T> is an interface, compared to List<T> being a concrete class), so the compiler allows it. In the particular case of LINQ's OrderBy it'll certainly fail, as it doesn't returns a list at all.

To actually get a list, you can use yet another LINQ method, ToList:

List<DirectoryObjects> sort = dirObjList.OrderBy(ms => ms.name).ToList();

This will iterate the original collection, sort it as you want, and store the result in a new List<T> object.

Alejandro
  • 7,290
  • 4
  • 34
  • 59