我有输入数据表:
Id Rating Col1 Col2
2000 A 10 20
2000 A 10 20
2000 A+ 5 15
2000 A+ 5 15
4000 A 10 20
4000 A 10 20
4000 A+ 5 15
4000 A+ 5 15
预期产出
我想根据特定 Id 和特定评级合并数据行。评级可能因 Id 而异。我在真实数据表中有超过 100 列,我也只想计算总和。
Id Rating Col1 Col2
2000 A 20 40
2000 A+ 10 30
4000 A 20 40
4000 A+ 10 30
首先我尝试使用这些方法。但是无法完成它们:
var Ids = dt.AsEnumerable().Select(row => row.Field<int>("Id")).Distinct();
foreach (var id in Ids)
{
//Get Ratings in the account
var ratings = dt.AsEnumerable().Where(row => row.Field<int>("Id") == id).Select(row => row.Field<string>("Rating")).Distinct();
foreach (var rating in ratings)
{
}
}
var groups = dt.AsEnumerable()
.GroupBy(row => new { Column1 = row.Field<string>("Id"), Column2 = row.Field<string>("Rating") });
.Select(group => new
{
Column1 = group.Key.Column1,
Column2 = group.Key.Column2,
Count = group.Count()
});
我怎样才能完成这个任务?
这应该是你所需要的:
var groups =
dt
.AsEnumerable()
.GroupBy(
row => new
{
Id = row.Field<string>("Id"),
Rating = row.Field<string>("Rating")
},
row => new
{
Col1 = row.Field<int>("Col1"),
Col2 = row.Field<int>("Col2")
})
.Select(group => new
{
group.Key.Id,
group.Key.Rating,
Col1 = group.Sum(x => x.Col1),
Col2 = group.Sum(x => x.Col2),
});