首页 > 解决方案 > 遍历字典元素并将它们添加到列表中

问题描述

当我遍历字典元素并将它们添加到列表中时。在这里我需要根据关键元素选择“项目”并将其存储到列表中。

  {"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);
    }

谢谢

标签: jsonasp.net-mvc

解决方案


如果我理解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();

推荐阅读