[英]Determine if Dictionary Contains All of a Set of Keys
I'm trying to figure out the best way to determine if a Dictionary<string, string>
object contains all of a set of string
objects as keys. 我试图找出确定Dictionary<string, string>
对象是否包含所有一组string
对象作为键的最佳方法。
I'm probably not making any sense so here's some example code using a definite set of strings: 我可能没有任何意义,所以这里有一些使用一组确定字符串的示例代码:
public static bool ContainsKeys(this Dictionary<string, string> dictionary)
{
return dictionary.ContainsKey("fname") && dictionary.ContainsKey("lname") && dictionary.ContainsKey("address1") &&
dictionary.ContainsKey("city") && dictionary.ContainsKey("state") && dictionary.ContainsKey("zip");
}
The idea here is to accept an arbitrary set of strings as keys
and check if the keys of the Dictionary<string, string>
object contain all of the strings in keys
. 这里的想法是接受字符串任意一组作为keys
和检查的钥匙Dictionary<string, string>
对象包含所有字符串keys
。
I was trying to go down the LINQ road with this: 我试图沿着LINQ路走下去:
public static bool ContainsKeys(this Dictionary<string, string> dictionary, string[] keys)
{
var query = from entry in dictionary
where keys.Contains(entry.Key)
select entry;
return query.Any();
}
I have no idea if I'm on the right path though - I think this might work if I wanted to know if dictionary
contained any of those strings as keys. 我不知道我是否在正确的道路上 - 我认为如果我想知道dictionary
包含任何这些字符串作为键,这可能会有效。
Something like this should meet your requirement. 这样的事情应该符合你的要求。 Apply proper validations around your arguments, of course. 当然,在你的论点周围应用适当的验证。
return keys.Any()
&& keys.All(key => dictionary.ContainsKey(key));
Note: I include Any
because All
will return true if the source sequence (keys) is actually empty. 注意:我包含Any
因为如果源序列(键)实际为空,则All
将返回true 。 If you don't mind this, then eliminate the use of Any
. 如果你不介意这一点,那么就不再使用Any
。
LINQ is indeed good for this sort of thing: LINQ对于这类事情确实很好:
public static bool ContainsKeys(this Dictionary<string, string> dictionary, string[] keys)
{
return keys.All(dictionary.ContainsKey);
}
这应该这样做,只需使用Except
消除Dictionary
的键并检查是否遗留了任何内容;
return !keys.Except(dictionary.Keys).Any();
To expand on the accepted answer , here is the complete source code for an extension method that will work on ANY type of Dictionary, not just one with string keys: 要扩展已接受的答案 ,这里是扩展方法的完整源代码,它将适用于任何类型的Dictionary,而不仅仅是一个带有字符串键的字典:
using System.Linq;
namespace System.Collections.Generic
{
/// <summary>
///
/// </summary>
public static class IDictionaryExtensions
{
public static bool ContainsKeys<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, IEnumerable<TKey> keys)
{
return keys.Any() && keys.All(key => dictionary.ContainsKey(key));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.