如何在C#中比较两个字典元组的值

3

我有两个字典,每个字典都有一个键和一个值作为元组(两个值)。我想要做到以下几点:

  • 基于键比较两个字典。如果键匹配,则它们的元组应该被比较。
  • 如果两个字典包含不同的键,即不匹配的键,应该会出现错误。

可以使用linq表达式或简单的循环和检查来实现。

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


5
那么,你遇到了什么错误?发生了什么事情?你尝试了什么? - TheGeneral
我熟悉在C#中比较简单的字典,其中只有一个键和一个值。但是对于这种情况,我无法做到。 - Mojiz Mehdi
1
System.Tuple 类型族不支持 ==!= 运算符重载,这是很不幸的。然而,为了提高性能和易用性,建议您考虑使用 System.ValueTuple 类型族,它们支持 ==!= 运算符,并且可以简洁地写成 (string, string) 的形式,例如 Dictionary<string, (string, string)> - Aluan Haddad
4
只需使用一些陈旧的 for/foreach 循环和几个 if 语句 就可以开始了吗? - TheGeneral
1
你能告诉我们你期望的结果是什么吗?你是在检查字典是否相等(具有相同的键和相同键的元组)吗?元组中值的顺序重要吗? - M. Azyoksul
@ M. Azyoksul,确切地说,这就是我期望的结果。是的,尽管元组中只有两个值,但它们按照我通过数据库设置的顺序排列。 - Mojiz Mehdi
2个回答

2
你可以这样做:

你可以这样做:

using System.Linq;
using System.Collections.Generic;

public static class DictionaryExtensions {
    public static bool IsEqualTo(this Dictionary<string, Tuple<string, string>> dict1, Dictionary<string, Tuple<string, string>> dict2) {
        if (!Enumerable.SequenceEqual(dict1.Keys.OrderBy(x => x), dict2.Keys.OrderBy(x => x))) {
            return false;
        }
            
        foreach(var kvp in dict1) {
            var corresponding = dict2[kvp.Key];
            
            if (kvp.Value.Item1 != corresponding.Item1 || kvp.Value.Item2 != corresponding.Item2) {
                return false;
            }
        }
            
        return true;
    }
}

然后使用它:

        Dictionary<string, Tuple<string, string>> dict1= new Dictionary<string, Tuple<string, string>>();
        Dictionary<string, Tuple<string, string>> dict2= new Dictionary<string, Tuple<string, string>>();
        
        Console.WriteLine(dict1.IsEqualTo(dict2)); // True
        
        dict1["a"] = new Tuple<string, string>("a", "b");
        dict2["a"] = new Tuple<string, string>("a", "b");
        
        Console.WriteLine(dict1.IsEqualTo(dict2)); // True
        
        dict2["a"] = new Tuple<string, string>("a", "b2");
        
        Console.WriteLine(dict1.IsEqualTo(dict2)); // False

        dict2["a"] = new Tuple<string, string>("a", "b");
        dict2["b"] = new Tuple<string, string>("a", "b2");

        Console.WriteLine(dict1.IsEqualTo(dict2)); // False

更新 感谢 Aluan Haddad 指出的排序问题。


1
这是一个不错的方法,但我不相信键会被排序。你可能需要对它们进行排序或使用类似于 d1.Keys.Count != d2.Keys.Count || d1.Keys.Except(d2.Keys).Any() 的集合操作。 - Aluan Haddad

1
假设您想检查字典是否相等,您可以使用以下代码:
// Checks if the dictionaries are equal
public static bool AreDictionriesEqual(Dictionary<string, Tuple<string, string>> dict1, Dictionary<string, Tuple<string, string>> dict2)
{
    // Check if the number of items are the same
    if (dict1.Count != dict2.Count)
        return false;

    // Get set of keys in both dictionaries
    var dict1Keys = dict1.Select(item => item.Key);
    var dict2Keys = dict2.Select(item => item.Key);

    // Check if the set of keys are the same
    if (!dict1Keys.All(key => dict2Keys.Contains(key)))
        return false;

    // Check if the strings in tuples are the same
    foreach(var item in dict1)
    {
        // Get first items
        var string1_Dict1 = item.Value.Item1;
        var string1_Dict2 = dict2[item.Key].Item1;

        // Check first items
        if (!string1_Dict1.Equals(string1_Dict2))
            return false;

        // Get second items
        var string2_Dict1 = item.Value.Item2;
        var string2_Dict2 = dict2[item.Key].Item2;

        // Check second items
        if (!string2_Dict1.Equals(string2_Dict2))
            return false;
    }

    // If we reach end, return true
    return true;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接