首页 文章

自定义比较字典linq

提问于
浏览
1

我有两个字典如下:

字典1:

Dictionary<string, string> dict1 = new Dictionary<string, string>();

request.Add("key1", "value1");

request.Add("key2", "value2");    

request.Add("key3", "value3");

字典2:

Dictionary<string, string> request = new Dictionary<string, string>();

request.Add("key1", "value1");

request.Add("key2", "value2");

我需要使用LINQ查询和条件来比较以上两个词典:

1) All keys in dict2 should match with keys in dict1

2) The matched keys should have equivalent value

3) Even if the value of key2 in dict2 is empty, it should match

感谢上面的帮助 . 提前致谢 .

问候,

萨钦

1 回答

  • 2

    您可以使用Contains method and provide a custom IEqualityComparer,但更简单的方法是使用Any()

    var dict1 = new Dictionary<string, string>
    {
        {"key1", "value1"},
        {"key2", "value2"},
        {"key3", "value3"}
    };
    
    var dict2 = new Dictionary<string, string>
    {
        {"key1", "value1"},
        {"key2", "value2"}
    };
    
    dict2.All(k2 => 
            dict1.Any(k1 => k1.Key == k2.Key && 
                            (String.IsNullOrEmpty(k2.Value) || k1.Value == k2.Value)))
    

    我想空的你是指 null 或空字符串,因此我使用String.IsNullOrEmpty . 如果你想检查 null ,请改为使用简单的 k2.Value == null .

相关问题