C#Linq如何使用group by来获得所需的输出

时间:2016-08-11 10:19:19

标签: linq c#-4.0

我有以下课程

public class Product
{
    public string PNo {get;set;}
    public String GCode {get;set;}
    public IList<Detail> Details {get;set;}
}

public class Detail{
    public string Color {get;set;}
    public string Size {get;set;}
}

我的数据如下所示

PNO     GCode   Color   Size Amount
12345   GCC     A       L       1
12345   GCC     V       M       2 
12345   GCC     C       S       3
12345   GCC     D       XL      4
12345   GCC     E       XS      5

如何使用groupby获得以下输出,以便我的输出如下所示

预期产出:

{
PNO: 12345,
GCode: GCC,
options:[
            {Color:A, Size:L, Amount: 1},
            {Color:V, Size:M, Amount: 2},
            {Color:C, Size:S, Amount: 3},
            {Color:D, Size:XL, Amount: 4},
            {Color:E, Size:XS, Amount: 5}
        ]
}

由于

2 个答案:

答案 0 :(得分:2)

根据您定义的合同。我认为下面的代码片段可以生成你想要的JSON,我使用匿名对象很多,你可以用你的实体类替换。

 products.GroupBy(product => new
                  {
                      product.PNo,
                      product.GCode
                  })
         .Select(productGroup => new
         {
             productGroup.Key.PNo,
             productGroup.Key.GCode,
             options = productGroup.SelectMany(product => product.Details.Select(detail => new
             {
                 detail.Color,
                 detail.Size,
                 detail.Amount
             }))
         });

希望它有所帮助。

答案 1 :(得分:1)

这将为您提供预期的输出:

查询语法:

var result = (from item in collection
             group item by new { item.PNO, item.GCode } into grouping
             select new Product
             {
                 PNo = grouping.Key.PNO,
                 GCode = grouping.Key.GCode,
                 Details = grouping.Select(item => new Detail { Color = item.Color, Size = item.Size, Amount = item.Amount }).ToList()
             }).ToList();

方法语法:

var result = collection.GroupBy(item => new { item.PNO, item.GCode })
          .Select(grouping => new Product
          {
              PNo = grouping.Key.PNO,
              GCode = grouping.Key.GCode,
              Details = grouping.Select(item =>   new Detail { Color = item.Color, Size = item.Size, Amount = item.Amount }).ToList()
          }).ToList();

测试数据:

List<dynamic> collection = new List<dynamic>()
{
    new { PNO = "12345", GCode = "GCC", Color = "A", Size="L", Amount=1 },
    new { PNO = "12345", GCode = "GCC", Color = "V", Size="M", Amount=2 },
    new { PNO = "12345", GCode = "GCC", Color = "C", Size="S", Amount=3 },
    new { PNO = "12345", GCode = "GCC", Color = "D", Size="XL", Amount=4 },
    new { PNO = "12345", GCode = "GCC", Color = "E", Size="XS", Amount=5 },
};