我有一个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);
但我很确定我做错了。
我怎样才能做到这一点?
答案 0 :(得分:2)
为什么不只是Array
或List
?您的 JSON 看起来像一个对象数组,您可以像这样投影匿名类型: -
var result = res.GroupBy(m => m.id)
.Select(x => new
{
id = x.Key,
data = x.ToArray()
}).ToArray();