将System.Linq.IOrderedEnumerable <T>转换为List <T>

Bal*_*tar 5 .net c# linq

.NET编译器不会隐式转换System.Linq.IOrderedEnumerable<T>System.Collections.Generic.List<T>

一个明确的演员:

using System.Collections.Generic;

var items = new List<MyType>;

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

return (List<MyType>)selectedItems;
Run Code Online (Sandbox Code Playgroud)

发出警告:

Suspicious cast: there is no type in the solution which inherits from both System.Linq.IOrderedEnumerable<MyType> and System.Collections.Generic.List<MyType>
Run Code Online (Sandbox Code Playgroud)

这里的最佳做法是什么

Cro*_*ono 17

只需使用ToList扩展名:

return selectedItems.ToList();
Run Code Online (Sandbox Code Playgroud)

你应该知道:最佳实践(因为你问过)实际上会要你IEnumerable<MyType>在大多数情况下返回.因此,您可能希望以这种方式更改签名:

public IEnumerable<MyType> MyFunction()
{
    // your code here
}
Run Code Online (Sandbox Code Playgroud)

然后,如果需要,将函数的结果放在列表中:

var myList = MyFunction().ToList();
Run Code Online (Sandbox Code Playgroud)

除非你有一个非常精确的返回List<>类型的理由,我强烈建议你不要.

希望有所帮助.