首页 文章

使用LINQ自定义比较词典

提问于
浏览
1

我有两个字典如下:

//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查询和条件来比较以上两个词典:

  • All keys in dict2 should match with keys in dict1

  • The matched keys should have equivalent value

我尝试在字典上创建一个扩展方法,但它返回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]});
    }
}

1 回答

  • 2

    您可以使用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
    

相关问题