-1
我需要动态生成一个查询来访问数据表中的某些列。c# - 动态生成linq
string cols="row[Id],row[UserId], row[Code]";
var result= (from DataRow row in dt.Rows
select cols);
但这只返回“行[Id],行[UserId],行[代码]”。我如何访问这些列中的值?
我需要动态生成一个查询来访问数据表中的某些列。c# - 动态生成linq
string cols="row[Id],row[UserId], row[Code]";
var result= (from DataRow row in dt.Rows
select cols);
但这只返回“行[Id],行[UserId],行[代码]”。我如何访问这些列中的值?
我怀疑这个问题可以通过基于LINQ的解决方案来优雅地解决。使用循环和使用Item property访问DataRow的列可以很容易地解决这个问题。
public IEnumerable<object[]> GetValues(IList<string> columns, DataTable dt) {
foreach (var row in dt.Rows) {
var rowResult = new object[columns.Count];
for (var col = 0; col < columns.Count; col++) {
rowResult[col] = row.Item[columns[col]];
}
yield return rowResult;
}
}
为什么不把它放在字典中? Dictionary<string, object>
关键是列名称,值是列的值。
string[] cols = new string[] { "Id", "UserId", "Code" };
var result = (from DataRow row in dt.Rows
select cols.ToDictionary(c => c, c => row[c]));
的可能的复制[动态生成的LINQ查询(http://stackoverflow.com/questions/9505189/dynamically-generate-linq-queries) – user3114639
为什么这必须是“动态”? –
@BiesiGrr我得到的列只能在运行时选择。 – Madonna10