我有一个数据表,看起来像图片中的那个。
使用以下代码,我试图计算每个项目中每个客户ID的单位数。我的问题是我似乎无法排除重复的单元。
var projectsGroup = dt.AsEnumerable().GroupBy(g => g.Field<string>("Project"));
foreach (var projectGroup in projectsGroup)
{
var clientGroups = dt.AsEnumerable().GroupBy(g => g.Field<string>("ClientId"));
foreach (var clientGroup in clientGroups)
{
var test = dt.AsEnumerable()
.Where(r => r.Field<string>("ClientId") == clientGroup.Key && r.Field<string>("Project") == projectGroup.Key)
.Select(r => r.Field<string>("Project"));
// Console.WriteLine(test.FirstOrDefault() + " " + test.Count());
}
}
所以我的问题是,如何排除这些?
答案 0 :(得分:0)
尝试这样的事情:
var projectsGroups = dt.AsEnumerable()
.GroupBy(r => r.Field<string>("Project"))
.Select(pg => new {
Project = pg.Key,
Clients = pg.GroupBy(r => r.Field<string>("ClientId"))
.Select(cg => new {
ClientId = cg.Key,
UnitCount = cg.Select(r => r.Field<string>("Unit"))
.Distinct()
.Count()
})
})
.ToList();
foreach (var pg in projectsGroups) {
foreach (var client in pg.Clients) {
Console.WriteLine($"In Project {pg.Project}, Client {client.ClientId} has {client.UnitCount} unit{(client.UnitCount == 1 ? "" : "s")}");
}
}