BaltoStar
BaltoStar

Reputation: 8997

Convert System.Linq.IOrderedEnumerable<T> to List<T>

.NET compiler will not implicitly convert System.Linq.IOrderedEnumerable<T> to System.Collections.Generic.List<T>

An explicit cast:

using System.Collections.Generic;

var items = new List<MyType>;

var selectedItems =
  from item in items
  where item.Active 
  select item;

return (List<MyType>)selectedItems;

gives this warning:

Suspicious cast: there is no type in the solution which inherits from both System.Linq.IOrderedEnumerable and System.Collections.Generic.List

What is best practice here?

Upvotes: 10

Views: 33815

Answers (2)

Crono
Crono

Reputation: 10478

Simply use the ToList extension:

return selectedItems.ToList();

You should be aware though: best practice (since you asked) would actually want you to return an IEnumerable<MyType> in most cases. Therefore, you may want to change your signature in this way:

public IEnumerable<MyType> MyFunction()
{
    // your code here
}

And THEN, if you need to, have the function's result in a list:

var myList = MyFunction().ToList();

Unless you have a very precise reason of returning a List<> type, I strongly suggest that you don't.

Hope that helps.

Upvotes: 28

codekaizen
codekaizen

Reputation: 27429

Use the System.Linq.Enumerable.ToList<T>() extension:

selectedItems.ToList();

Upvotes: 4

Related Questions