[c#] LINQ select in C# dictionary

I have next dictionary in C#

Dictionary<string, object> subDictioanry = new Dictionary<string, object>();

List<Dictionary<string, string>> subList = new List<Dictionary<string, string>>();

subList.Add(new Dictionary<string, string>(){
    {"valueLink", "link1"},
    {"valueTitle","title1"}
});
subList.Add(new Dictionary<string, string>(){
    {"valueLink", "link2"},
    {"valueTitle","title2"}
});
subList.Add(new Dictionary<string, string>(){
    {"valueLink", "link3"},
    {"valueTitle","title3"}
});

subDictioanry.Add("title", "title");
subDictioanry.Add("name", "name");
subDictioanry.Add("fieldname1", subList);

Dictionary<string, object> exitDictionary = new Dictionary<string, object>();
exitDictionary.Add("first", subDictioanry);
exitDictionary.Add("second", subDictioanry);

Is it possible to get all "valueTitle" with help of LINQ select?

UPDATE: Sorry, i should write it first - i need to get result from exitDictionary, not from subList

This question is related to c# linq dictionary

The answer is


If you are searching by the fieldname1 value, try this:

var r = exitDictionary
   .Select(i => i.Value).Cast<Dictionary<string, object>>()
   .Where(d => d.ContainsKey("fieldname1"))
   .Select(d => d["fieldname1"]).Cast<List<Dictionary<string, string>>>()
   .SelectMany(d1 => 
       d1
        .Where(d => d.ContainsKey("valueTitle"))
        .Select(d => d["valueTitle"])
        .Where(v => v != null)).ToList();

If you are looking by the type of the value in the subDictionary (Dictionary<string, object> explicitly), you may do this:

var r = exitDictionary
   .Select(i => i.Value).Cast<Dictionary<string, object>>()
   .SelectMany(d=>d.Values)
   .OfType<List<Dictionary<string, string>>>()
   .SelectMany(d1 => 
       d1
        .Where(d => d.ContainsKey("valueTitle"))
        .Select(d => d["valueTitle"])
        .Where(v => v != null)).ToList();

Both alternatives will return:

title1
title2
title3
title1
title2
title3

This will return all the values matching your key valueTitle

subList.SelectMany(m => m).Where(kvp => kvp.Key == "valueTitle").Select(k => k.Value).ToList();

var res = exitDictionary
            .Select(p => p.Value).Cast<Dictionary<string, object>>()
            .SelectMany(d => d)
            .Where(p => p.Key == "fieldname1")
            .Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
            .SelectMany(l => l)
            .SelectMany(d=> d)
            .Where(p => p.Key == "valueTitle")
            .Select(p => p.Value)
            .ToList();

This also works, and easy to understand.


One way would be to first flatten the list with a SelectMany:

subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python