2011-10-27 5 views
4

LINQクエリの結果をループする方法はありますか?このようなLINQクエリ列(行ではない)を介したループ

何か:すべて事前に

DataRow dr = new DataRow(); 
string foobar = dr[columns[i]; 

ありがとう:

var results= from a in dt.AsEnumerable() 
        where a.Field<int>("id") == i 
        select new 
        { 
         id= a.Field<int>("id"), 
         a= a.Field<double>("a"), 
         b = a.Field<double>("b") 
        }; 

IEnumerable<string> colNames = results.First().GetType().GetProperties() 
                 .Select(p => p.Name); 

string[] columns = colNames.ToArray(); 

int i = 0; 
foreach (var row in results) 
{ 
    for (int i = 0; i < columns.Count(); i++) 
    { 
     string foobar = (string)row[columns[i]]; 
     i++; 
    } 
} 

基本的に、私は、機能の次の並べ替えを複製します。

+1

あなたがする必要がありますキャスト、だから 'string foobar =(string)dr [columns [i]; – xanatos

+0

多分この回答はあなたを助けるでしょうhttp://stackoverflow.com/questions/1882935/c-sharp-anonymous-type-foreach-looping –

+0

@キント、良い点、よく作られた。 – CatchingMonkey

答えて

3

元のLINQ文を変更して、探していることを実行できるデータ構造を作成するオプションがある場合は、間違いなくそのことをお勧めします。

ない場合、あなたは自分の名前で、あなたの匿名型の性質を調べるためにリフレクションを使用する必要があり、その後、反射によってこれらのプロパティの値を取得します:

PropertyInfo[] columns = results.First().GetType().GetProperties(); 
    ... 
      string foobar = columns[i].GetValue(row, null); 
+0

私は本当にオプションを持っていないhavent。しかし、私はプロパティを取得するために少しの反射を使用して、私はちょうど今それらと何をすべきか分からない! – CatchingMonkey

+0

@CatchingMonkey:私の更新を見る – StriplingWarrior

2
Action<string> processColumName = (cname) => 
          { 
           // do anything you want with a column name 
           string foo = (string) Row[cname]; 
          }; 

results.First() 
     .GetType() 
     .GetProperties() 
     .Select(p => p.Name) 
     .ToList().ForEach(processColumName); 
関連する問題