LINQ之ToList

259 阅读1分钟

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

ToList()

使用ToList()可以将IEnumerable<T>转换为list。

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[] { "正一郎", "清次郎", "誠三郎", "征史郎" };

        List<float>     listA  = dataA.ToList();
        List<int>       listB  = dataB.ToList();
        List<string>    listC  = dataC.ToList();

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

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

        System.Console.WriteLine( "dataC:{0}", dataC.Text() );
        System.Console.WriteLine( "listC:{0}", listC.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],
listA:[0.1], [2.3], [6.7],
dataB:[0], [1], [2], [3], [4], [5], [6], [7], [8], [9],
listB:[0], [1], [2], [3], [4], [5], [6], [7], [8], [9],
dataC:[正一郎], [清次郎], [誠三郎], [征史郎],
listC:[正一郎], [清次郎], [誠三郎], [征史郎],