c# 使用linq对数据表中的多列进行分组
我的数据表中有三列:字符串、日期时间和小数。我想按字符串和小数列进行分组,对于分组的行,我想对小数值求和。我知道如何进行求和部分,但是如何对数据表中的两个不同列进行分组?
这是我到目前为止无法正常工作的代码:
var newSort = from row in objectTable.AsEnumerable()
group row by new {ID = row.Field<string>("resource_name"), time1 = row.Field<DateTime>("day_date")} into grp
orderby grp.Key
select new
{
resource_name1 = grp.Key.ID,
day_date1 = grp.Key.time1,
Sum = grp.Sum(r => r.Field<Decimal>("actual_hrs"))
};
I have three columns in a datatable: string, DateTime, and decimal. I want to group by the string and decimal column, and for the rows grouped I want to sum the decimal values. I know how to do the sum part, but how do you group two different columns in a datatable?
This is my code so far which doesn't work properly:
var newSort = from row in objectTable.AsEnumerable()
group row by new {ID = row.Field<string>("resource_name"), time1 = row.Field<DateTime>("day_date")} into grp
orderby grp.Key
select new
{
resource_name1 = grp.Key.ID,
day_date1 = grp.Key.time1,
Sum = grp.Sum(r => r.Field<Decimal>("actual_hrs"))
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你没有向我们讲述完整的故事。除了
orderby
不使用匿名类型(您提供的代码无法编译)之外,您的查询应该按照您想要的方式工作。我只是将其放入 LINQPad:...我得到了这些结果:
I don't think you're giving us the full story. Other than
orderby
not working with anonymous types (the code you gave wouldn't have compiled), your query should work the way you want. I just put this in LINQPad:... and I got these results:
使用此代码
use this code
对于那些想要在 Vb.net 中找到解决方案的人,这里有一个示例:
For those that want a solution in Vb.net, here is an example: