json - 遍历字典元素并将它们添加到列表中
问题描述
当我遍历字典元素并将它们添加到列表中时。在这里我需要根据关键元素选择“项目”并将其存储到列表中。
{"0":["1234","2222","4321","211000","90024","12","2121","322223","2332","3232"],"1":["0856","6040222","175002","23572","","","","","",""]}
List<string> strlist;
strlist = new List<string>();
var jr = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(paramValue);
foreach (var item in jr)
{
// Need to add item on basis of Key
// Can we include any where clause
strlist.AddRange(item.Value);
}
谢谢
解决方案
如果我理解Need to add item on basis of Key
正确的含义,那么这应该对您有用:
List<string> strlist = new List<string>();
var jr = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(paramValue);
foreach (var item in jr)
{
if(item.Key == "someKey")
{
strlist.AddRange(item.Value);
}
}
或者,如果您有多个要匹配的键:
List<string> strlist = new List<string>();
var jr = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(paramValue);
List<string> targetKeys = new List<string>{"someKey", "anotherKey", "oneAwesomeKey"};
foreach (var item in jr)
{
if(targetKeys.Contains(item.Key))
{
strlist.AddRange(item.Value);
}
}
此处的第一个示例显示仅当键等于定义的字符串时才添加字典值(someKey
在此示例中)。如果字典键包含在定义的字符串列表中,则第二个示例显示添加字典值。
您还可以使用 linq 来实现此目的,如下所示:
var jr = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(paramValue);
var strlist= jr.Where(x => x.Key == "someKey").SelectMany(x => x.Value).ToList();
同样匹配多个键:
var jr = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(paramValue);
List<string> targetKeys = new List<string>{"someKey", "anotherKey", "oneAwesomeKey"};
var strlist= jr.Where(x => targetKeys.Contains(x.Key)).SelectMany(x => x.Value).ToList();
推荐阅读
- c - fork 停止子创建后的 for() 循环
- python - SciKit Learn Logistic Regression One-verse-the-rest 问题
- node.js - Node.js aws-sdk:找不到模块'concat-stream'
- python - 匀称的STRtree太慢了?
- javascript - react-native-highcharts,无法访问事件加载函数内的状态变量,并且可以访问事件加载函数外的 addPoints()
- url - 使用唯一 URL 进行身份验证有哪些安全问题
- php - AdminLTE 侧边栏活动菜单不会动态更改
- java - 按方法名称的 Spring Data Jpa 查询在 LocalDate 的 BETWEEN 中无法正常工作
- python - 如何在 groupby+apply 中返回另一列的值
- mongodb - Mongodb 聚合 - 根据时间获取所有最后插入的文档组