个性化阅读
专注于IT技术分析

LINQ ToArray()方法

点击下载

本文概述

LINQ中的ToArray()运算符用于将集合中的输入元素转换为Array。

LINQ ToArray()运算符的语法

使用LINQ ToArray()运算符将集合转换为数组的语法。

C#代码

string[] countryarray = countries.ToArray();

在以上语法中, 我们将”国家”的集合转换为数组。

方法语法中的LINQ ToArray()运算符示例

In this example, we are using LINQ ToArray() operator in method syntax to convert the input collection items to new array.

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 string type containing the data.
            string[] countries = { "Uk", "Us", "Russia", "India", "Argentina", "Australia", "China" };
//countries.ToArray() is used to convert the collection of data into the form of array
            string[] countryarray = countries.ToArray();
//foreach loop is used to print the name of the countries
            foreach (string s in countryarray)
            {
                Console.WriteLine(s);
            }
                Console.ReadLine();
        }
    }
}

在上面的示例中, 我们有一个字符串类型” countries”的列表。通过使用ToArray()方法, 我们将”国家”列表的列表转换为Array。为了访问这些元素, 我们在foreach循环中迭代了该数组并将其显示在屏幕上。

输出

LINQ ToArray()方法

查询语法中的LINQ ToArray()运算符

在查询语法中使用LINQ ToArray()运算符的示例是:

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 = { "India", "China", "US", "Russia", "Argentina", "Australia", "UK" };
//query syntax is used to convert the collection of data into the form of array
            string[] countrArray = (from x in countries select x).ToArray();
            foreach (string s in countrArray)
            {
                Console.WriteLine(s);
            }
                Console.ReadLine();
        }
    }
}

输出

LINQ ToArray()方法

赞(0)
未经允许不得转载:srcmini » LINQ ToArray()方法

评论 抢沙发

评论前必须登录!