欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用 LINQ 转换为数组的方法

最编程 2024-08-10 17:27:55
...

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

ToArray()

您可以从序列(例如数组或列表)创建数组。
List<T>IEnumerable<T>可以使用ToArray()直接转换为数组。
MSDN

using System.Linq;
using System.Collections;
using System.Collections.Generic;

public static class Program
{
    static void Main( string[] args )
    {
        List<float>         dataA   = new List<float>() { 0.1f, 2.3f, 6.7f };
        IEnumerable<int>    dataB   = Enumerable.Range( 0, 10 );
        string[]            dataC   = new string[] { "正一郎", "清次郎", "誠三郎", "征史郎" };

        float[]     arrayA  = dataA.ToArray();
        int[]       arrayB  = dataB.ToArray();
        string[]    arrayC  = dataC.ToArray();

        System.Console.WriteLine( "dataA :{0}",  dataA.Text() );
        System.Console.WriteLine( "arrayA:{0}", arrayA.Text() );

        System.Console.WriteLine( "dataB :{0}",  dataB.Text() );
        System.Console.WriteLine( "arrayB:{0}", arrayB.Text() );

        System.Console.WriteLine( "dataC :{0}",  dataC.Text() );
        System.Console.WriteLine( "arrayC:{0}", arrayC.Text() );

        System.Console.ReadKey();
    }

    public static string Text( this IEnumerable i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }

}

dataA :[0.1], [2.3], [6.7],
arrayA:[0.1], [2.3], [6.7],
dataB :[0], [1], [2], [3], [4], [5], [6], [7], [8], [9],
arrayB:[0], [1], [2], [3], [4], [5], [6], [7], [8], [9],
dataC :[正一郎], [清次郎], [誠三郎], [征史郎],
arrayC:[正一郎], [清次郎], [誠三郎], [征史郎],

推荐阅读