将System.Linq.IOrderedEnumerable <t>转换为List <t> </t> </t>

时间:2014-03-13 16:32:24

标签: c# .net 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;

发出警告:

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

这里的最佳做法是什么

2 个答案:

答案 0 :(得分:17)

只需使用ToList扩展程序:

return selectedItems.ToList();

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

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

然后,如果需要,将功能的结果列在一个列表中:

var myList = MyFunction().ToList();

除非您有一个非常准确的原因要求退回List<>类型,否则我强烈建议您不要这样做。

希望有所帮助。

答案 1 :(得分:3)

使用System.Linq.Enumerable.ToList<T>()扩展程序:

selectedItems.ToList();
相关问题