C#Linq如何使用group by来获得所需的输出 [英] C# Linq how to use group by to get the desired output

查看:276
本文介绍了C#Linq如何使用group by来获得所需的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类

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

如何获得

预期输出:

{
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}
        ]
}

感谢

推荐答案

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

Given the contract you defined. I think below code snippet is OK to generate the JSON you want, I use anonymous object a lot, you can replace with you entity class.

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

希望它有帮助。

这篇关于C#Linq如何使用group by来获得所需的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆