首页 > 解决方案 > LINQ to JSON 数组查询

问题描述

我有一个 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 个

我在想也许我的查询需要一个“不同的”,但我不确定。

标签: c#jsonlinq

解决方案


这是 Select 的问题。您告诉它让在数组中找到的每个值都成为它自己的项目。实际上,您需要将所有值组合成每个特征的字符串。这是你的做法

var features = from f in autoFeatures.Select(feat => string.Join(",",feat["features"].Values<string>()))
                       group f by f into grp
                       orderby grp.Count() descending
                       select new { indFeature = grp.Key, count = grp.Count() };

产生以下输出

sunroof,mag wheels, 2
sunroof, 1
mag wheels, 1
sunroof,mag wheels,spoiler, 1
sunroof,spoiler, 1
spoiler, 1

推荐阅读