如何使用linq从嵌套字典中选择所有值?

时间:2018-07-17 09:50:39

标签: c# linq

我的Super类属性是

public List<Test> Super { get; set; }

我的Test类是

public class Test
{
    public int Id { get; set; }

    public Dictionary<string, string> dict { get; set; }
}

如何从关键字为"description"的字典中选择所有值

3 个答案:

答案 0 :(得分:4)

您可以使用SelectMany获取所有字典,例如:

var values = Super
    .SelectMany(s => s.dict)
    .Where(s => s.Key == "description")
    .Select(s => s.Value);

答案 1 :(得分:1)

您可以做类似的事情

var dict = (from p in obj.Super
                   where p.dict != null && p.dict.ContainsKey(keyToCheck)
                   select p.dict[keyToCheck]);

完整代码:

    void Main()
    {
        string keyToCheck = "description";
        var obj = new Super1();
        var dict = (from p in obj.Super
                   where p.dict != null && p.dict.ContainsKey(keyToCheck)
                   select p.dict[keyToCheck]);
        Console.Write(dict);
    }

    public class Super1
    {
        public List<Test> Super { get; set; } = new List<Test>(){
            new Test(){ Id = 1, dict = new Dictionary<string,string>() {
                {"description","abc"},{"description1","1"},{"description2","2"},{"description3","3"}
            }},
            new Test(){ Id = 2, dict = new Dictionary<string,string>() {
                {"description","xyz"},{"description4","4"},{"description5","5"},{"description6","6"}
            }
        }};
    }

    public class Test
    {
        public int Id { get; set; }

        public Dictionary<string, string> dict { get; set; }
    }

输出:

abc 
xyz 

答案 2 :(得分:0)

您可以尝试的是

List<string> AllValues = new List<string>();
Super.ForEach(x => 
      {
         if(x.dict.ContainsKey("description")
         {
             AllValues.AddRange(x.dict["description"]);
         } 
      });