1

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"
        }
        ]
    ]
}
1
  • 4
    I tried to fix your question formatting for you, but your JSON isn't entirely valid. Can you please update it and fix the formatting? Thanks! Note that an array directly in a JSON object without a key isn't valid. Commented Jul 23, 2019 at 5:28

1 Answer 1

1

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
        })
    ));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.