C# 如何比较字典键中的字符串数组
我创建的字典如下:C# 如何比较字典键中的字符串数组,c#,winforms,C#,Winforms,我创建的字典如下: Dictionary dic=newdictionary() 我有这样一个字符串数组: string[]str=新字符串[]{“str1”、“str2”、“str3”} 现在我想检查dic键是否包含str的所有元素,而不使用循环。最好的方法是什么?。谢谢。如果您想知道所有字典是否包含所有键: bool allContainsAll = dic.All(dictonary => str.All(dictonary.ContainsKey)); 如果您想知道字符串是否在任
Dictionary dic=newdictionary()代码>
我有这样一个字符串数组:
string[]str=新字符串[]{“str1”、“str2”、“str3”}
现在我想检查dic
键是否包含str
的所有元素,而不使用循环。最好的方法是什么?。谢谢。如果您想知道所有字典是否包含所有键:
bool allContainsAll = dic.All(dictonary => str.All(dictonary.ContainsKey));
如果您想知道字符串是否在任何字典键中:
var allDictKeys = new HashSet<string>(dic.SelectMany(d => d.Keys));
bool allContainsAll = str.All(allDictKeys.Contains);
var allDictKeys=newhashset(dic.SelectMany(d=>d.Keys));
bool allContainsAll=str.All(allDictKeys.Contains);
请注意,LINQ也使用循环,您只是看不到它们。这是一个使用LINQ的解决方案,至少没有可见循环,但内部LINQ使用循环
Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("str1", 1);
dic.Add("str2", 2);
dic.Add("str3", 3);
string[] str = new string[] { "str1", "str2", "str3" };
bool ContainsAll = str.All(dic.ContainsKey); //true
Dictionary dic=newdictionary();
dic.添加(“str1”,1);
dic.添加(“str2”,2);
dic.添加(“str3”,3);
字符串[]str=新字符串[]{“str1”、“str2”、“str3”};
bool ContainsAll=str.All(dic.ContainsKey)//真的
“不使用循环”是不可能的,即使LINQ也使用循环。另外,这是一个字典[]
,您想知道一个字典是否包含所有键,所有字典是否包含所有键,或者所有字典是否包含所有键,但总数除外(例如,第一个字典包含str1
,第二个字典包含str2
等)?因为字典不是嵌套的,所以接受的答案不会编译List@ByyoTimSchmelter是对的,OP改变了问题“d”和“s”是什么?@Ajope:那是一个。d
和s
是投影对象的变量。在本例中,使用字典和字符串。我重命名了dictionary变量并删除了s
,因为在本例中可以直接传递方法。