使用LINQ自定义比较词典



我有两个字典如下:

//Dictionary 1:
Dictionary<string, string> dict1 = new Dictionary<string, string>();
dict1 .Add("key1", "value1");
dict1 .Add("key2", "value2");    
dict1 .Add("key3", "value3");
//Dictionary 2 :
Dictionary<string, string> request = new Dictionary<string, string>();
request.Add("key1", "value1");
request.Add("key2", "value2");          

我需要使用LINQ查询比较以上两个字典,条件是:

  1. dict2中的所有密钥都应与dict1中的密钥匹配

  2. 匹配的密钥应具有等效值

我尝试在dictionary上创建一个扩展方法,但它返回false,因为dict1包含一个额外的对。

public static class DictionaryExtension
{
    public static bool CollectionEquals(this Dictionary<string, string> collection1,
                                        Dictionary<string, string> collection2)
    {
        return collection1.ToKeyValue().SequenceEqual(collection2.ToKeyValue());
    }
    private static IEnumerable<object> ToKeyValue(this Dictionary<string, string>  collection)
    {
        return collection.Keys.OrderBy(x => x).Select(x => new {Key = x, Value = collection[x]});
    }
}

您只需使用All()扩展方法来测试集合中的所有元素是否满足特定条件。

var dict1 = new Dictionary<string, string>
{
    {"key1", "value1"},
    {"key2", "value2"},
    {"key3", "value3"}
};
var dict2 = new Dictionary<string, string>
{
    {"key1", "value1"},
    {"key2", "value2"}
};
dict2.All(kvp => dict1.Contains(kvp)); // returns true

另一种(可能更快,但不那么时髦)方法是将两个哈希集进行交集:

var h1 = new HashSet<KeyValuePair<string, string>>(dict1);
var h2 = new HashSet<KeyValuePair<string, string>>(dict2);
h1.IntersectWith(h2);
var result = (h1.Count == h2.Count); // contains true

相关内容

  • 没有找到相关文章

最新更新