2016-03-28 14 views
0

DataTableがあり、テキストボックスの入力と一致する複数の列をDataTableで選択したいとします。以下のコードは1列のみを選択します。LINQを使用してDataTableで2つ以上の列を選択

var result = from data in mDataTable.AsEnumerable() 
       where data.Field<string>("Code") == txtCode.Text 
       select data.Field<string> ("Description"); 

    foreach (var res in result) { 

     txtxDescription.Text = res.ToString(); 
    } 

LINQを使用してDataTableで2つ以上の列を選択するにはどうすればよいですか?

+1

あなたが行全体を選択しないのはなぜ?そうすれば、必要なすべての列にアクセスできます。 –

答えて

2

なぜ完全な行(DataRowオブジェクト)を選択してからそれらのすべての必要な値を取るのですか?

var rows = mDataTable.AsEnumerable() 
        .Where(data => data.Field<string>("Code") == txtCode.Text); 

foreach(DataRow r in rows) 
{ 
    txtxDescription.Text = r.Field<string>("Description"); 
} 

別のオプションは、匿名オブジェクトにデータを投影することである。

var result = from data in mDataTable.AsEnumerable() 
      where data.Field<string>("Code") == txtCode.Text 
      select new 
        { 
         Description = data.Field<string> ("Description"), 
         Code = data.Field<string> ("Code") 
        }; 

foreach (var res in result) 
{ 
    // last value always replace `txtxDescription.Text` ?? 
    txtxDescription.Text = res.Description; 
    txtxCode.Text = res.Code; 
} 
関連する問題