如何比较字典键内的字符串数组
本文关键字:字符串 数组 字典 何比较 比较 | 更新日期: 2023-09-27 18:15:00
我创建了一个这样的字典:
Dictionary<string, int> dic = new Dictionary<string, int>();
我有一个像这样的字符串数组:
string[] str = new string[]{"str1","str2","str3"}
现在我想检查dic
键是否包含str
的所有元素而不使用循环。做这件事的最好方法是什么?谢谢。
这是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
如果您想知道所有字典是否包含所有键:
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);
注意LINQ也使用循环,你只是看不到它们。
如果你想比较字典和字符串数组,你可以使用SequenceEqual:
bool AreEqual = dic.Keys.SequenceEquals(str);
或者如果它们不在同一序列中:
HashSet<string> set = new HashSet<string>(dic.Keys);
bool AreEqual = set.SetEquals(str);