当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。