Help us understand the problem. What is going on with this article?

テーブル構造のファイルを読み込む

More than 5 years have passed since last update.

趣旨

Qiita: 二次元Listジェネリックにファイル読み込み

この記事は、上記事のIF版です。
元記事ではList<List<string>>へ格納していますが、この記事ではDataTableを使用します。

読込部

Program.cs
static DataTable LoadTable( string path, Encoding encoding )
{
    var rows = from x in File.ReadLines( path, encoding )
                select x.Split( new[ ] { '\t' }, StringSplitOptions.None );

    var dataTable = new DataTable( );
    using ( var enumerator = rows.GetEnumerator( ) )
    {
        if ( enumerator.MoveNext( ) )
        {
            var columns = from x in enumerator.Current
                            select new DataColumn( x );

            dataTable.Columns.AddRange( columns.ToArray( ) );
        }
        while ( enumerator.MoveNext( ) )
        {
            dataTable.Rows.Add( enumerator.Current );
        }
    }
    return dataTable;
}

表示部

Program.cs
static void Main( string[ ] args )
{
    using ( var table = LoadTable( "sample.txt", Encoding.UTF8 ) )
    {
        var columns = from x in table.Columns.Cast<DataColumn>( )
                        select x.ColumnName;

        Console.WriteLine( string.Join( " ", columns ) );

        var rows = from x in table.Rows.Cast<DataRow>( )
                    select x.ItemArray;

        foreach ( var row in rows )
        {
            Console.WriteLine( string.Join( " ", row ) );
        }
    }
    Console.ReadKey( );
}

kuchikios
✌('ω')✌
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away