如何在Linq to SQL中循环列名
var foo = (from f in db.bar select f).ToList()
我想要做的是遍历每个列名,即
foreach bar d in foo
{
foreach column in d
{<do something>}
}
这可能吗?
答案 0 :(得分:3)
这是一个将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
}
答案 1 :(得分:2)
如果您还没有将映射模型扩展到其他字段,或者也不介意迭代它们,则可以使用:
var fields = typeof(Product).GetFields();
foreach(var item in db.Products)
{
foreach(var f in fields)
{
Console.WriteLine(f.Name + ": " + f.GetValue(item));
}
}
答案 2 :(得分:-1)
以下是我认为您想要的一个示例,如果这不足以让您入门,请详细说明您的需求。
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]);
}
}