Linq在C#行中循环通过列 [英] Linq Loop Through Columns in Row C#

查看:360
本文介绍了Linq在C#行中循环通过列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Linq到SQL中遍历列名

How do I loop through column names in Linq to SQL

var foo = (from f in db.bar select f).ToList()

我想做的是遍历每个列名,即

What I want to do is loop through each column name, i.e.

    foreach bar d in foo
{
    foreach column in d
      {<do something>}
}

有可能吗?

推荐答案

以下是一种将LINQ-to-sql查询作为可枚举的字典的方法:

Here's a method that returns a LINQ-to-sql query as an enumerable of dictionaries:

IEnumerable<IDictionary<string, object>> GetValues<T>(DataContext context,
                                                         IQueryable<T> query)
    where T : class
{
    var propertyInfos = typeof(T).GetProperties().ToDictionary (pi => pi.Name);
    foreach(var entity in context.GetTable<T>())
    {
        yield return (context.Mapping.GetTable(typeof(T)).RowType.DataMembers
           .Where(dm => !dm.IsAssociation).Select (dm => dm.Name)
        .Select(name => new { name, 
                              value = propertyInfos[name].GetValue(entity, null)
                            })
        .ToDictionary (x => x.name, y => y.value));
    }
}

您从字典中获得列名和值:

You get the column names and the values from the dictionaries:

var foo = (from f in db.bar select f);
foreach(var dictionary in GetValues(db, foo))
{
    // do something with dictionary keys and/or values
}

这篇关于Linq在C#行中循环通过列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆