c#使用linq按数据表中的多个列进行分组 [英] c # using linq to group by multiple columns in a datatable
问题描述
我在datatable中有三列:string,DateTime和decimal。我想通过字符串和十进制列进行分组,对于分组的行,我想将十进制值相加。我知道如何做总和部分,但是如何在数据表中分组两个不同的列?
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?
这是迄今为止我的代码无法正常工作的代码: / p>
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"))
};
推荐答案
我不认为你给我们全文除了 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:
var objectTable = new DataTable();
objectTable.Columns.Add("resource_name",typeof(string));
objectTable.Columns.Add("day_date",typeof(DateTime));
objectTable.Columns.Add("actual_hrs",typeof(decimal));
objectTable.Rows.Add(1, DateTime.Today, 1);
objectTable.Rows.Add(2, DateTime.Today, 2);
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
select new
{
resource_name1 = grp.Key.ID,
day_date1 = grp.Key.time1,
Sum = grp.Sum(r => r.Field<Decimal>("actual_hrs"))
};
newSort.Dump();
...我得到这些结果:
... and I got these results:
resource_name1 | day_date1 | Sum
1 | 7/1/2011 12:00:00 AM | 1
2 | 7/1/2011 12:00:00 AM | 2
这篇关于c#使用linq按数据表中的多个列进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!