Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用GROUPBY将c#列表转换为json_C# - Fatal编程技术网

使用GROUPBY将c#列表转换为json

使用GROUPBY将c#列表转换为json,c#,C#,我已经将datatable转换为c#list,我需要将该列表转换为json格式,但是json响应是一行一行地出现的。我需要不重复id的json格式,如下所示 ri是包含数据的列表类型 var listResp = r1.GroupBy(x => x.StoreId).SelectMany(x=>x).ToList(); 此代码将数据表转换为列表 public static List<AllInvoicesModel> InvoiceDataList(System.Dat

我已经将datatable转换为c#list,我需要将该列表转换为json格式,但是json响应是一行一行地出现的。我需要不重复id的json格式,如下所示

ri是包含数据的列表类型

var listResp = r1.GroupBy(x => x.StoreId).SelectMany(x=>x).ToList();
此代码将数据表转换为列表

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;
}
但是我需要这种格式的响应,并将单独的storeid分组

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

有一个LINQ扩展名
.GroupBy
,可以为您实现这一点

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

我试图为您修复问题格式,但您的JSON并不完全有效。你能更新它并修改格式吗?谢谢请注意,JSON对象中没有键的直接数组是无效的。
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
        })
    ));