首页 > 解决方案 > 如何在 C# 中比较两个字典?

问题描述

  1. 字典有不同的计数和不同的顺序
  2. 如果列表 A 和列表 B 的键匹配,我想带列表 B 的值并修改列表 A 的值。

示例代码:

public static List<Dictionary<string, string>> ListDicOne = new List<Dictionary<string, string>>();

public static List<Dictionary<string, string>> ListDicTwo = new List<Dictionary<string, string>>();

(...)
ListDicOne[0].Add("ABCD", "");          // empty value
ListDicOne[1].Add("ABCD", "");          
ListDicOne[2].Add("EFGH", "test");

ListDicTwo[0].Add("AABC", "oooo");
ListDicTwo[1].Add("ABCD", "WOW");
ListDicTwo[2].Add("CCDD", "haha");
ListDicTwo[3].Add("CCDD", "haha");

预期结果值:

// Console Write key and value of ListDicA 

ABCD \t WOW
ABCD \t WOW
EFGH \t test

标签: c#dictionary

解决方案


我会猜测一下,假设您真的只想处理两个字典,而不是处理许多单项字典的两个列表,这根本没有任何意义。

首先,字典应该这样声明(我也假设它们不必是公开的):

private static Dictionary<string, string> ListDicOne = new Dictionary<string, string>();

private static Dictionary<string, string> ListDicTwo = new Dictionary<string, string>();

然后,用法可能是这样的:

ListDicOne.Add("AABC", ""); // I changed the key, they must be unique
ListDicOne.Add("ABCD", "");
ListDicOne.Add("EFGH", "test");

ListDicTwo.Add("AABC", "oooo");
ListDicTwo.Add("ABCD", "WOW");
ListDicTwo.Add("CCDD", "haha");
ListDicTwo.Add("CCDE", "haha"); // I changed the key, they must be unique

foreach (var item in ListDicTwo)
{
    if (ListDicOne.ContainsKey(item.Key))
        ListDicOne[item.Key] = ListDicTwo[item.Key];
}

的最终状态ListDicOne是:

("AABC", "oooo")
("ABCD", "WOW")
("EFGH", "test")

我希望你觉得这个澄清和有用。

** 更新 **

考虑具有非唯一键的字符串列表:

private static List<Tuple<string, string>> ListOne = new List<Tuple<string, string>>();

private static List<Tuple<string, string>> ListTwo = new List<Tuple<string, string>>();

(...)

ListOne.Add(Tuple.Create("ABCD", ""));
ListOne.Add(Tuple.Create("ABCD", ""));
ListOne.Add(Tuple.Create("EFGH", "test"));

ListTwo.Add(Tuple.Create("AABC", "oooo"));
ListTwo.Add(Tuple.Create("ABCD", "WOW"));
ListTwo.Add(Tuple.Create("CCDD", "haha"));
ListTwo.Add(Tuple.Create("CCDD", "haha"));

foreach (var l2item in ListTwo)
{
    for (int i = 0; i < ListOne.Count; i++)
    {
        if (ListOne[i].Item1 == l2item.Item1)
            ListOne[i] = Tuple.Create(l2item.Item1, l2item.Item2);
    }
}

注 1:元组是不可变的,因此在更改时需要创建一个新元组Item2

foreach注2:当需要改变迭代列表时不能使用,所以我使用了a for

注意3:如果ListTwo碰巧有两个不同的键值组合(假设不会发生),第二个将覆盖第一个。

这是您的测试值的最终结果:

("ABCD", "WOW")
("ABCD", "WOW")
("EFGH", "test")

推荐阅读