当我遍历字典元素并将它们添加到列表中时。在这里,我需要根据关键元素选择“项目”并将其存储到列表中。
{"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);
}
谢谢
答案 0 :(得分:0)
如果我了解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();