Casting IEnumerable to List
我想知道是否可以将IEnumerable转换为List。 除了将每个项目复制到列表中之外,还有什么办法吗?
如前所述,使用
这正是其他答案所暗示的,但更清晰。这是反汇编,所以你可以肯定:
1 2 3 4 5 6 7 8 | public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) { if (source == null) { throw Error.ArgumentNull("source"); } return new List<TSource>(source); } |
//使用System.Linq;
使用.ToList()方法。在System.Linq命名空间中找到。
1 | var yourList = yourEnumerable.ToList(); |
https://docs.microsoft.com/en-us/dotnet/api/system.linq?view=netcore-2.2
正如其他人建议的那样,只需在可枚举对象上使用
1 | var myList = myEnumerable.ToList() |
但是,如果您的
'IEnumerable' does not contain a definition for 'ToList'
你可能错过了
1 | using System.Linq |
创建一个新的List并将旧的IEnumerable传递给它的初始化器:
1 2 |
不,您应该复制,如果您确定该引用是对列表的引用,您可以像这样转换
1 | List<int> intsList = enumIntList as List<int>; |