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


LINQ ToArray()用法及代碼示例

LINQ 中的 ToArray() 運算符用於將集合中的輸入元素轉換為數組。

LINQ ToArray() 運算符的語法

使用 LINQ ToArray() 運算符將集合轉換為數組的語法。

C# 代碼

string[] countryarray = countries.ToArray();

在上麵的語法中,我們將 "countries" 的集合轉換為數組。

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

在上麵的例子中,我們有一個字符串類型為 "countries." 的 List 通過使用 ToArray() 方法,我們將 "countries" List 的列表轉換為一個數組。為了訪問這些元素,我們在 foreach 循環中迭代了數組並將其顯示在屏幕上。

輸出:

LINQ ToArray() Method

查詢語法中的 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() Method



相關用法


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