2011-10-27 20 views
4

是否有可能以及如何循環LINQ查詢的結果?通過LINQ查詢列循環(不是行)

事情是這樣的:

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++; 
    } 
} 

從本質上講,我希望複製下面的排序功能:

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

感謝所有提前。

+1

你必須cast,所以'string foobar =(string)dr [columns [i]; – xanatos

+0

也許這個答案會幫助你http://stackoverflow.com/questions/1882935/c-sharp-anonymous-type-foreach-looping –

+0

@xantos,好點,做得很好。 – CatchingMonkey

回答

3

如果您可以選擇更改原始LINQ語句以生成允許您執行所需操作的數據結構,那麼我肯定會這樣做。

如果沒有,你需要通過反射使用反射他們的名字來查找您的匿名類型的屬性,然後獲得這些屬性的值:

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

我沒有真的有選擇沒有。然而,我用了一些反射來獲得屬性,我現在不知道該怎麼做! – 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);