Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

.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 warning :

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

What is best practice here

like image 317
BaltoStar Avatar asked Mar 13 '14 16:03

BaltoStar


2 Answers

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.

like image 73
Crono Avatar answered Oct 22 '22 09:10

Crono


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

selectedItems.ToList();
like image 44
codekaizen Avatar answered Oct 22 '22 08:10

codekaizen