我是 Linq 的新手,正在尝试按我的 Linq 查询进行分组,但收到不包含字段值的错误。
下面是我的 linq 查询。谁能帮我解决这个问题。
var name = dt1.AsEnumerable()
.Where(p => (int)p["Age"] >= 29)
.GroupBy(p =>p.Field<string>("Role"))
.Select(p => new{ID = p.Field<int>("ID"),Name =p.Field<string>("Name"),Role = p.Field<string>("Role"),Age = p.Field<int("Age")});
最佳答案
正确的代码:
var name = dt1.AsEnumerable()
.Where(p => p.Field<int>("Age") >= 29)
.GroupBy(p =>p.Field<string>("Role"))
.Select(q => q.Select(p => new{ID = p.Field<int>("ID"),Name =p.Field<string>("Name"),Role = p.Field<string>("Role"),Age = p.Field<int>("Age")}));
解释:
- GroupBy 将创建
IEnumerable<IGrouping<string,DataRow>>
在这种情况下 - 当你做
Select
, 你得到IGrouping
,您需要进一步做Select
得到确切的元素DataRow
用于创建结果Anonymous Type
在这种情况下
关于c# - 在 LinQ 中使用 Group By 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40584455/