OrElse
OrElse

Reputation: 9999

How can i select all values from a nested dictionary with linq?

My Super class property is

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

while myTest class is

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

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

How can i select all values from the dictionary where the key name is "description"

Upvotes: 3

Views: 2234

Answers (3)

Nitin S
Nitin S

Reputation: 7600

You can do something like

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

Complete code:

    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; }
    }

Output:

abc 
xyz 

Upvotes: 1

Lucifer
Lucifer

Reputation: 1600

You can try is

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

Upvotes: 0

DavidG
DavidG

Reputation: 119176

You can use SelectMany to get all the dictionaries, for example:

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

Upvotes: 5

Related Questions