按多列对DataTable进行分组,并使用限制

时间:2017-05-16 13:34:31

标签: c# linq

我有datatable列,如下所示:

Agent   Country City
A       India   Delhi
B       India   Delhi
C       India   Delhi
D       India   Delhi
E       India   Delhi
AA      India   Mumbai
BB      India   Mumbai
CC      India   Mumbai
DD      India   Lucknow
EE      India   Lucknow
FF      India   Lucknow
GG      India   Lucknow

我需要的是:

Agent       Country City
A,B,C       India   Delhi
D,E         India   Delhi
AA,BB,CC    India   Mumbai
DD,EE,FF    India   Lucknow
GG          India   Lucknow

我希望将代理连接到最大限制为3.我尝试使用以下代码:

var result = dt1.AsEnumerable()
        .GroupBy(x => new { Country = x.Field<string>("Country"), 
                            City = x.Field<string>("City") })
        .Select(x => new 
           {
               Agent = String.Join(",",x.Select(z => z.Field<string>("Agent"))),
               Country = x.Key.Country,
               City = x.Key.City
           });

我得到以下结果

Agent            Country    City
A,B,C,D,E        India      Delhi
AA,BB,CC         India      Mumbai
DD,EE,FF,GG      India      Lucknow

你能帮我找到一种方法,这样我就可以将代理的限制设置为3,然后将新行设置为接下来的3个代理。

这只是一个示例场景。真实的数据有很多代理,我需要将它们限制在可配置的限制。谢谢。

1 个答案:

答案 0 :(得分:1)

尝试此查询,技巧是SelectMany和内部GroupBy整数除法结果:

var result = dt1.AsEnumerable()
    .GroupBy(x => new { Country = x.Field<string>("Country"), City = x.Field<string>("City") })
    .SelectMany(group => group
        .Select((row, index) => new { Row = row, Index = index })
        .GroupBy(x => x.Index / 3)
        .Select(g => new
        {
            Agents = string.Join(",", g.Select(x => x.Row.Field<string>("Agent"))),
            group.Key.Country, group.Key.City
        }));