gpt4 book ai didi

c# - 将 System.Linq.IOrderedEnumerable 转换为 List

转载 作者:太空狗 更新时间:2023-10-29 22:06:32 26 4
gpt4 key购买 nike

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

这里的最佳实践是什么

最佳答案

只需使用 ToList 扩展名:

return selectedItems.ToList();

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

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

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

var myList = MyFunction().ToList();

除非您有非常明确的理由返回 List<>类型,我强烈建议你不要。

希望对您有所帮助。

关于c# - 将 System.Linq.IOrderedEnumerable<T> 转换为 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22385046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com