c# - 如何在 C# 中比较两个字典?
问题描述
- 字典有不同的计数和不同的顺序
- 如果列表 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
解决方案
我会猜测一下,假设您真的只想处理两个字典,而不是处理许多单项字典的两个列表,这根本没有任何意义。
首先,字典应该这样声明(我也假设它们不必是公开的):
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")
推荐阅读
- swift - 后台线程中使用的 SimplePing (macOS) 不起作用。有哪些替代方案?
- android - 如何从Android中的源位图裁剪圆形位图?
- angular - 在应用程序中带有路由的 Angular 2+ 选项卡
- ios - 将应用商店中的 IOS 应用限制为特定设备
- python - Numpy throwing TypeError: cannot unpack non-iterable NoneType object
- swift - (WkWebView) 当我通过输入标签上传文件时,它发生了问题
- php - Laravel 数据库存储会话
- php - 如何使用 PHP 添加 Active Directory 身份验证密码?
- r - 错误无法将“mads”类强制转换为 data.frame
- javascript - JAVASCRIPT - 如何每秒更新变量