c# - 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 个
我在想也许我的查询需要一个“不同的”,但我不确定。
解决方案
这是 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
推荐阅读
- tinymce - 在 Keystone js 中禁用 TinyMCE
- java - Google Play Games 交互式登录提示实现?
- casablanca - 使用 ctrl+c 取消时抛出异常
- r - R 减运算产生不精确的值
- python - 从字符串中删除多个字符(形成一个单词)
- python - 使用 Fabric 的 Django 自动部署
- python - 将 sql 代码转换为 python pandas 数据帧操作
- r - 当rollends =(FALSE,FALSE)时R data.table Rolling Join
- struts2 - 在对话框struts2中显示标签表
- optaplanner - 在 MoveIteratorFactory 中使用 Optaplanner 的 NearbySelection