铸造IEnumerable T.列出< T> [英] Casting IEnumerable<T> to List<T>
问题描述
我想知道是否可以将IEnumerable
强制转换为List
.除了将每个项目复制到列表中之外,还有其他方法吗?
I was wondering if it is possible to cast an IEnumerable
to a List
. Is there any way to do it other than copying out each item into a list?
推荐答案
如已经建议的那样,使用yourEnumerable.ToList()
.它通过您的IEnumerable
枚举,并将内容存储在新的List
中.您不一定要复制现有列表,因为您的IEnumerable
可能会懒惰地生成元素.
As already suggested, use yourEnumerable.ToList()
. It enumerates through your IEnumerable
, storing the contents in a new List
. You aren't necessarily copying an existing list, as your IEnumerable
may be generating the elements lazily.
这正是其他答案所暗示的内容,但更为清楚.这是反汇编,因此您可以确定:
This is exactly what the other answers are suggesting, but clearer. Here's the disassembly so you can be sure:
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
return new List<TSource>(source);
}
这篇关于铸造IEnumerable T.列出< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!