【发布时间】:2020-01-04 01:11:56
【问题描述】:
我有一个 JSON 数据示例,我正在使用 NewtonSoft 将其转换为 JArray。
string jsonString = @"[{'features': ['sunroof','mag wheels']},{'features': ['sunroof']},{'features': ['mag wheels']},{'features': ['sunroof','mag wheels','spoiler']},{'features': ['sunroof','spoiler']},{'features': ['sunroof','mag wheels']},{'features': ['spoiler']}]";
我正在尝试检索最常一起请求的功能。基于上述数据集,我的预期输出将是:
天窗,磁轮,2
天窗, 1
磁轮 1
天窗、磁轮、扰流板、1
天窗,扰流板,1
扰流板,1
但是,我的 LINQ 生锈了,我用来查询 JSON 数据的代码返回的是单个功能的计数,而不是一起选择的功能:
JArray autoFeatures = JArray.Parse(jsonString);
var features = from f in autoFeatures.Select(feat => feat["features"]).Values<string>()
group f by f into grp
orderby grp.Count() descending
select new { indFeature = grp.Key, count = grp.Count() };
foreach (var feature in features)
{
Console.WriteLine("{0}, {1}", feature.indFeature, feature.count);
}
实际输出:
天窗,5
磁轮,4
扰流板,3
我在想也许我的查询需要一个“不同的”,但我不确定。
【问题讨论】:
-
var features = JsonConvert.DeserializeObject<List<Dictionary<string, string[]>>>(jsonString).SelectMany(d => d).GroupBy(k => string.Concat(k.Value.OrderBy(s => s))).Select(g => new { Feature = g.Key, Count = g.Count() }).OrderByDescending(a => a.Count);。值字符串在内部预先排序(以生成忽略字符串值位置的有序组)