LINQ select in C# dictionary
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
One way would be to first flatten the list with a SelectMany
:
subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));
This will return all the values matching your key valueTitle
subList.SelectMany(m => m).Where(kvp => kvp.Key == "valueTitle").Select(k => k.Value).ToList();