[英]c# - dynamically generate linq
I need to dynamically generate a query to access certain columns from a datatable.我需要动态生成查询以访问数据表中的某些列。
string cols="row[Id],row[UserId], row[Code]";
var result= (from DataRow row in dt.Rows
select cols);
but this only returns "row[Id],row[UserId], row[Code]".但这只会返回“row[Id],row[UserId],row[Code]”。 How can I access the values in those columns?
如何访问这些列中的值?
I doubt this problem can be solved elegantly with a linq-based solution.我怀疑这个问题能否通过基于 linq 的解决方案优雅地解决。 It can be solved pretty easily using a loop and by accessing the column of the DataRow using the Item property .
使用循环和使用Item 属性访问 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;
}
}
Why not putting it in a dictionary?为什么不把它放在字典里?
Dictionary<string, object>
the key is the column name and the value is the value of the column. 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]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.