在 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。