简体   繁体   中英

Converting c# list to json with group by

I have converted the datatable to c# list , I need to convert the list to json format, But the json response is coming of all rows one by one. I need the json format with no repeating of the id's which was shown below.

ri is the list type which contains the data .

var listResp = r1.GroupBy(x => x.StoreId).SelectMany(x=>x).ToList();

this code converts the datatable to list.

public static List<AllInvoicesModel> InvoiceDataList(System.Data.DataTable dataTable)
{
    var retList = new List<AllInvoicesModel>();
    for (int i = 0; i < dataTable.Rows.Count; i++)
    {
        var row = dataTable.Rows[i];

        var temp = new AllInvoicesModel()
        {
            StoreId = Convert.ToInt32(row["StoreId"]),
            storyname= Convert.ToString(row["storyname"]),
        };

        retList.Add(temp);
    }

    return retList;
}

actual result:

[
    {
        "storeId": 0,
        "storeName": "sdfsfd",
        "partyCode": "82"
    },
    {
        "storeId": 0,
        "storeName": "sfsdfs",
        "partyCode": "827"
    },
    {
        "storeId": 1,
        "storeName": "Anfffsdfs",
        "partyCode": "827",
        "displayPartyCode": "2477"
    }
]

But I need the response in this format, with grouping the separate storeid's

{
    [
    "storedId":0,
    "isSelected":true,
    "invoiceslist":[
        {
            "storeName": "sdfsfd",
            "partyCode": "82"
        },
        {
            "storeName": "Ansdf",
            "partyCode": "827"
        }
        ],
    "storedId":1,
    "isSelected":true,
    "invoiceslist":[
        {
            "storeName": "sdfsfd",
            "partyCode": "82"
        }
        ]
    ]
}

There's a LINQ extension .GroupBy that will do this for you.

var grouped = retList
    .GroupBy(r => { r.storedId, r.isSelected })
    .Select(g => new {
        storedId = g.Key.storedId,
        isSelected = g.Key.isSelected,
        invoicesList = g.Select(i => new {
            storeName = i.storeName,
            partyCode = i.partyCode
        })
    ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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