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 查询来比较上述两个字典:

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

  2. 匹配的键应该具有相同的值

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

1 回答 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
于 2013-02-05T12:17:29.930 回答