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

标签 c# dictionary

我有两个字典,一个键和一个值作为元组(两个值)。我想执行以下操作:

  • 根据关键字比较两个字典。如果键匹配,则应该比较它们的元组。
  • 如果两个字典包含不同的键,即不匹配的键,它应该给出一个错误。

它可以是 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>>();

最佳答案

你可以这样做:

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 指出排序问题。

关于c# - 如何在 C# 中比较两个字典元组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63293003/

相关文章:

c# - 如何使用 Entity Framework 对延迟加载的实体进行排序?

python - 创建字典时“int”对象不可迭代

c# - Azure ServiceBusProcessor 需要很长时间才能停止

c# - 在多个分隔符上分隔字符串时,如何知道使用了哪个分隔符? (C#)

从嵌套字典中检索单个级别的 Pythonic 方法

python - 文件中的词频计数器

python - 字典如何在python中添加键?

json - 将本地字典复制到全局字典中

c# - 如何获取 Window 实例的 hWnd?

c# - 如何从 C# 中的 HTTP Post 访问 header 信息?