C# C字典中的LINQ选择
我有下一本C语言词典C# C字典中的LINQ选择,c#,linq,dictionary,C#,Linq,Dictionary,我有下一本C语言词典 Dictionary<string, object> subDictioanry = new Dictionary<string, object>(); List<Dictionary<string, string>> subList = new List<Dictionary<string, string>>(); subList.Add(new Dictionary<string, str
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);
是否可以在LINQ select的帮助下获取所有valueTitle
更新:
抱歉,我应该先写它-我需要从exitDictionary而不是从subList获取结果这将返回与您的key valueTitle匹配的所有值
一种方法是首先使用SelectMany将列表展平:
如果要按fieldname1值搜索,请尝试以下操作:
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();
两种选择都将返回:
title1
title2
title3
title1
title2
title3
这同样有效,并且易于理解。这是错误的。kvp将不是一个KeyValuePair,而是一个字典。您缺少了一个用于展平列表的SelectMany。如果您使用类而不是字典,这将更容易进行推理。只是说说而已。
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();
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();
title1
title2
title3
title1
title2
title3
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();