Tengo el siguiente diccionario en 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);
¿Es posible obtener todos los "valueTitle" con la ayuda de LINQ select?
UPDATE: Lo siento, debería escribirlo antes - necesito obtener el resultado de exitDictionary, no de subList
Si está buscando por el valor fieldname1
, pruebe esto:
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();
Si está buscando por el tipo de valor en el subDictionary
(Dictionary<string, object>
explícitamente), puede hacer esto:
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();
Ambas alternativas devolverán:
title1
title2
title3
title1
title2
title3