16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-06-01

趣旨

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( );
}

16
16
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?