[英]How verify if a List of Dictionary contains a Dictionary with specific key - C#
I have a List of Dictionaries: 我有一个词典列表:
List<Dictionary<string, int>> listDic = new List<Dictionary<string, int>>();
How do I verify if listDic contains a Dictionary with Key == "apple", for example? 例如,如何验证listDic是否包含键==“ apple”的Dictionary?
You can use .Any
on the outer dictionary and .ContainsKey
on the inner ones. 您可以使用
.Any
对外部字典和.ContainsKey
在内的。 Something like this: 像这样:
var containsApple = listDic.Any(x => x.ContainsKey("Apple"));
This should result in true
if any one or more of the dictionaries in listDic
contains the key "Apple"
. 如果
listDic
中的任何一个或多个词典包含键"Apple"
则结果为true
。
Essentially you start with your overall problem: 本质上,您从总体问题开始:
How do I verify if listDic contains a Dictionary with Key == "apple"
如何验证listDic是否包含键==“ apple”的字典
And break it into two smaller, simpler, easily findable on Google problems: 并将其分为两个更小,更简单,更容易找到的Google问题:
The first one involves calling .ContainsKey
on the dictionary, the second one involves calling .Any
on the collection. 第一个需要调用
.ContainsKey
词典中,第二个涉及调用.Any
的集合。 After that, you simply combine the two. 之后,您只需将两者结合即可。
If you can use linq
, you can do this by using .Any()
: 如果可以使用
linq
,则可以使用.Any()
:
bool containsKey = listDic.Any(x => x.ContainsKey("apple"));
This checks the collection one by one until the key is found. 这将一个接一个地检查集合,直到找到密钥为止。 If the key is found on the second item,
.Any()
only iterated over two items and not the whole collection. 如果在第二个项目上找到了密钥,则
.Any()
仅迭代两个项目,而不是整个集合。
尝试使用LINQ
bool result = listDic.Any(x => x.ContainsKey("Apple"));
bool contains = listDic.Any(x => x.ContainsKey("apple"));
List<Dictionary<string, int>> listDic = new List<Dictionary<string, int>>();
Dictionary<string, int> di = new Dictionary<string, int>();
di.Add("apple", 1);
listDic.Add(di);
di = new Dictionary<string, int>();
di.Add("mango", 2);
di = new Dictionary<string, int>();
di.Add("grapes", 3);
Dictionary<string, int> item = listDic.Where(c => c.ContainsKey("apple")).FirstOrDefault();
if (item != null)
{
string key = item.FirstOrDefault().Key;
int value = item.FirstOrDefault().Value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.