Linq循环遍历行中的列
本文关键字:循环 遍历 Linq | 更新日期: 2023-09-27 18:06:33
如何通过Linq中的列名循环到SQL
var foo = (from f in db.bar select f).ToList()
我要做的是遍历每个列名,即
foreach bar d in foo
{
foreach column in d
{<do something>}
}
这可能吗?
下面是一个方法,它将LINQ-to-sql查询作为字典的可枚举对象返回:
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));
}
}
从字典中获取列名和值:
var foo = (from f in db.bar select f);
foreach(var dictionary in GetValues(db, foo))
{
// do something with dictionary keys and/or values
}
如果您还没有使用其他字段扩展您的映射模型,或者不介意对它们进行迭代,您可以使用:
var fields = typeof(Product).GetFields();
foreach(var item in db.Products)
{
foreach(var f in fields)
{
Console.WriteLine(f.Name + ": " + f.GetValue(item));
}
}
这是我认为你想要的一个例子,如果这还不足以让你开始,请解释你需要更详细的内容。
var myTable = new DataTable();
myTable.Columns.Add("Column One");
myTable.Columns.Add("Column Two");
var newRow = myTable.NewRow();
newRow[0] = 11111;
newRow[1] = 22222;
myTable.Rows.Add(newRow);
var newRow2 = myTable.NewRow();
newRow2 [0] = 33333;
newRow2 [1] = 44444;
myTable.Rows.Add(newRow2);
foreach (var row in myTable.AsEnumerable())
{
foreach (DataColumn column in myTable.Columns)
{
Console.WriteLine("Column {0}, Row {1}, Value {2}", column.ColumnName, myTable.Rows.IndexOf(row), row[column]);
}
}