将Dictionary <string,?>从LINQ返回到SQL

时间:2018-02-27 10:35:59

标签: c# json linq json.net

我有一个LINQ to SQL查询,其最终select就是这样:

 select new{
                id = <result id>,
                serial = <result serial>,
                type = <result type>,
                model = <result model>
        }

在此之后,我想在本地对结果进行分组。 我需要一个像这样的输出JSON:

[   
    {
        "id":group_id, 
        "data":[
                {...},
                {...}
               ]
    }
]

到目前为止,我已经设法做了这样的事情:

var res = q.ToList();
var dict = res.GroupBy(m => m.machine).ToDictionary(g => g.Key, g => g.ToList());

然后我用

序列化它
Newtonsoft.Json.JsonConvert.SerializeObject(dict);

但我很确定我做错了。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

为什么不只是ArrayList?您的 JSON 看起来像一个对象数组,您可以像这样投影匿名类型: -

var result = res.GroupBy(m => m.id)
                .Select(x => new 
                           {
                               id = x.Key,
                               data = x.ToArray()
                           }).ToArray();