使用LINQ自定义比较词典

时间:2013-02-05 12:08:26

标签: linq dictionary

我有两个词典如下:

//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. 匹配的键应具有等效值

  3. 我尝试在字典上创建一个扩展方法,但它返回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 个答案:

答案 0 :(得分: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