在 LINQ 中,ToList 运算符从给定的源中获取元素,并返回一个新的 List。因此,在这种情况下,输入将转换为 List 类型。
LINQ ToList() 运算符的语法
使用 LINQ ToList() 将输入集合转换为列表的语法。
C# 代码
List<string> result = countries.ToList();
在上面的语法中,我们使用 LINQ ToList() 运算符将 "countries" 集合转换为列表。
方法语法中 ToList() 运算符的示例
在方法语法中使用 LINQ ToList() 将输入集合转换为 List 的示例。
C# 代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//create array countries of type string containing the collection of data
string[] countries = { "US", "UK", "India", "Russia", "China", "Australia", "Argentina" };
//countries.ToList() convert the collection of data into the list.
List<string> result = countries.ToList();
//foreach loop is used to print the information of the student
foreach (string s in result)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
}
输出:

在上面的示例中,我们使用 LINQ ToList() 方法将国家集合转换为 List。
查询语法中的 ToList() 运算符示例
在查询语法中使用 LINQ ToList() 运算符的示例
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string[] countries = { "US", "UK", "India", "Russia", "China", "Australia", "Argentina" };
//used query syntax to convert the collection of the data into the list
List<string> result = (from x in countries select x).ToList();
foreach (string s in result)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
}
输出:

相关用法
- LINQ ToLookup()用法及代码示例
- LINQ ToArray()用法及代码示例
- LINQ ToDictionary()用法及代码示例
- LINQ AsEnumrable()用法及代码示例
- LINQ ElementAtOrDefault()用法及代码示例
- LINQ Count()用法及代码示例
- LINQ Single()用法及代码示例
- LINQ sum()用法及代码示例
- LINQ Min()用法及代码示例
- LINQ LastOrDefault()用法及代码示例
- LINQ FirstOrDefault()用法及代码示例
- LINQ GroupBy()用法及代码示例
- LINQ Cast()用法及代码示例
- LINQ Max()用法及代码示例
- LINQ Aggregate()用法及代码示例
- LINQ DefaultfEmpty()用法及代码示例
- LINQ Last()用法及代码示例
- LINQ ElementAt()用法及代码示例
- LINQ OfType()用法及代码示例
- Lodash _.sampleSize()用法及代码示例
注:本文由纯净天空筛选整理自 LINQ ToList() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。