遍历LINQ查询列(而不是行)

5

是否可以循环遍历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];

Thanks all in advance.


1
你需要进行强制类型转换,所以代码应该是 string foobar = (string)dr[columns[i]]; - xanatos
也许这个答案可以帮到你:http://stackoverflow.com/questions/1882935/c-sharp-anonymous-type-foreach-looping - Ivan Crojach Karačić
@xantos,说得好,点子不错。 - CatchingMonkey
3个回答

4

如果您有更改原始LINQ语句以生成允许您执行所需操作的数据结构的选项,我强烈建议这样做。

如果没有,则需要使用反射按名称查找匿名类型的属性,然后通过反射获取这些属性的值:

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

我实际上没有选择权。但是,我已经使用了一些反射来获取属性,现在我不知道该怎么做了! - CatchingMonkey

3
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);

0
我将根据其他人的答案进行翻译(下面会留下一个链接),稍作修改后如下:stovroz 以下是代码:
foreach(var item in db.Products) {
   System.Reflection.PropertyInfo[] fields = Product.GetType().GetProperties(); 
   foreach(var f in fields) {
      Console.WriteLine(f.Name + ": " + f.GetValue(item));
   }  
} 

实际上我一直在寻找这样的解决方案来使用动态LINQ,而这个人救了我的一天。非常感谢他!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接