铸造IEnumerable T.列出< T> [英] Casting IEnumerable<T> to List<T>

查看:101
本文介绍了铸造IEnumerable T.列出< 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.列出&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆