Linq - Tolist
Enumerable.ToList<TSource> 方法
从 IEnumerable<T> 创建一个 List<T>。
命名空间: System.Linq
程序集: System.Core(在 System.Core.dll 中)
类型参数
- TSource
-
source 中的元素的类型。
参数
- source
- 类型:System.Collections.Generic.IEnumerable<TSource>
要从其创建 List<T> 的 IEnumerable<T>。
使用说明
在 Visual Basic 和 C# 中,可以在 IEnumerable<TSource> 类型的任何对象上将此方法作为实例方法来调用。当使用实例方法语法调用此方法时,请省略第一个参数。有关详细信息,请参阅扩展方法 (Visual Basic)或扩展方法(C# 编程指南)。异常 | 条件 |
---|---|
ArgumentNullException |
source 为 null。 |
ToList<TSource>(IEnumerable<TSource>) 方法强制进行直接查询计算,并返回一个包含查询值的 List<T>。 可将此方法追加到您的查询,以获得查询结果的缓存副本。
ToArray<TSource> 具有类似行为,但它返回一个数组,而非一个 List<T>。
下面的代码示例演示如何使用 ToList<TSource> 强制进行直接查询计算并返回一个包含查询结果的 List<T>。
string[] fruits = { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" }; List<int> lengths = fruits.Select(fruit => fruit.Length).ToList(); foreach (int length in lengths) { Console.WriteLine(length); } /* This code produces the following output: 5 12 6 5 6 9 5 10 */