无涯教程-Linq ToArray()方法

87 阅读1分钟

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

LINQ ToArray()运算符的语法

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

C#代码

string[] countryarray = countries.ToArray();

In the above syntax, we are converting the collection of "countries" to an Array.

方法语法中的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) { //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(); } } }

In the above example, we have a List of type string "countries." By using the ToArray() method, we converted the list of "countries" List to an Array. To access these elements, we have iterated the array in a foreach loop and displayed it on the screen.

输出:

LINQ ToArray() Method

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

The example of using 查询语法中的Linq ToArray()运算符 is:

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




参考链接

www.learnfk.com/linq/linq-t…