关于c#:将IEnumerable < T >转换为List < T >

Casting IEnumerable to List

我想知道是否可以将IEnumerable转换为List。 除了将每个项目复制到列表中之外,还有什么办法吗?


如前所述,使用yourEnumerable.ToList()。它通过IEnumerable枚举,将内容存储在新的List中。您不一定要复制现有列表,因为您的IEnumerable可能会懒惰地生成元素。

这正是其他答案所暗示的,但更清晰。这是反汇编,所以你可以肯定:

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


正如其他人建议的那样,只需在可枚举对象上使用ToList()方法:

1
var myList = myEnumerable.ToList()

但是,如果您的IEnumerable对象没有ToList()方法,并且您收到如下错误:

'IEnumerable' does not contain a definition for 'ToList'

你可能错过了System.Linq命名空间,所以只需添加它:

1
using System.Linq

创建一个新的List并将旧的IEnumerable传递给它的初始化器:

1
2
    IEnumerable<int> enumerable = GetIEnumerable< T >();
    List<int> list = new List<int>(enumerable);


不,您应该复制,如果您确定该引用是对列表的引用,您可以像这样转换

1
List<int> intsList = enumIntList as List<int>;