當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


LINQ ToList()用法及代碼示例

在 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() Method

在上麵的示例中,我們使用 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 ToList() Method



相關用法


注:本文由純淨天空篩選整理自 LINQ ToList() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。