1

私は次のように2つの辞書を持っています:

//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クエリを使用して、上記の2つの辞書を比較する必要があります。

  1. dict2のすべてのキーは、dict1のキーと一致する必要があります

  2. 一致したキーは同等の値である必要があります

辞書に拡張メソッドを作成しようとしましたが、dict1に1つの余分なペアが含まれているため、falseが返されます。

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

別の(おそらくより高速ですが、それほどファンキーではない)アプローチは、2つのハッシュセットの交差を行うことです。

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 に答える