Reputation: 254
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"
}
]
]
}
Upvotes: 1
Views: 949
Reputation: 1730
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
})
));
Upvotes: 1