简体   繁体   English

C# 数据表按计数和不同分组

[英]C# datatable Group by count and distinct

I have a datatable that looks like the one in the picture.我有一个数据表,看起来像图片中的那个。

在此处输入图片说明

With the below code I'm trying to count how many units each client id has in the each project.使用下面的代码,我试图计算每个项目中每个客户端 ID 有多少个单元。 My problem is I can't seem to exclude the duplicate units.我的问题是我似乎无法排除重复的单位。

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());
    }
}

So my question is, how can I exclude these from being counted?所以我的问题是,如何将这些排除在计数之外?

Try something like this:尝试这样的事情:

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")}");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM