Как сравнить значения кортежей двух словарей в c# - PullRequest
3 голосов
/ 07 августа 2020

У меня есть два словаря с одним ключом и значением в виде кортежа (два значения). Хочу сделать следующее:

  • сравнить оба словаря по ключу. Если ключи совпадают, то их кортеж следует сравнивать.
  • также, если оба словаря содержат разные ключи, т.е. несогласованный ключ, это должно выдать ошибку.

Это может быть любое выражение 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>>();

PS Я новичок в программировании, поэтому заранее спасибо.

Ответы [ 2 ]

2 голосов
/ 07 августа 2020

Вы можете сделать это так:

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 голос
/ 07 августа 2020

Предполагая, что вы хотите проверить, равны ли словари или нет, вы можете использовать следующий код

// 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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...