C#字典中的LINQ选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19726288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ select in C# dictionary
提问by user2944829
I have next dictionary in C#
我有 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?
是否有可能在 LINQ select 的帮助下获得所有“valueTitle”?
UPDATE: Sorry, i should write it first - i need to get result from exitDictionary, not from subList
更新:对不起,我应该先写 - 我需要从 exitDictionary 中获取结果,而不是从 subList
采纳答案by Alex Filipovici
If you are searching by the fieldname1
value, try this:
如果您按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();
If you are looking by the type of the value in the subDictionary
(Dictionary<string, object>
explicitly), you may do this:
如果您正在按subDictionary
(Dictionary<string, object>
明确)中的值类型查找,您可以这样做:
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
回答by gleng
This will return all the values matching your key valueTitle
这将返回与您的键匹配的所有值 valueTitle
subList.SelectMany(m => m).Where(kvp => kvp.Key == "valueTitle").Select(k => k.Value).ToList();
回答by Arran
One way would be to first flatten the list with a SelectMany
:
一种方法是首先使用以下命令展平列表SelectMany
:
subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));