gpt4 book ai didi

c# - 在 C# 中测试字典之间的相等性

转载 作者:IT王子 更新时间:2023-10-29 03:47:20 25 4
gpt4 key购买 nike

假设字典键和值正确实现了 equals 和 hash 方法,那么测试两个字典是否相等的最简洁有效的方法是什么?

在这种情况下,如果两个字典包含相同的键集(顺序不重要),并且对于每个这样的键,它们都同意值,则它们被认为是相等的。

以下是我想出的一些方法(可能还有更多):

public bool Compare1<TKey, TValue>(
Dictionary<TKey, TValue> dic1,
Dictionary<TKey,TValue> dic2)
{
return dic1.OrderBy(x => x.Key).
SequenceEqual(dic2.OrderBy(x => x.Key));
}

public bool Compare2<TKey, TValue>(
Dictionary<TKey, TValue> dic1,
Dictionary<TKey, TValue> dic2)
{
return (dic1.Count == dic2.Count &&
dic1.Intersect(dic2).Count().
Equals(dic1.Count));
}

public bool Compare3<TKey, TValue>(
Dictionary<TKey, TValue> dic1,
Dictionary<TKey, TValue> dic2)
{
return (dic1.Intersect(dic2).Count().
Equals(dic1.Union(dic2).Count()));
}

最佳答案

dic1.Count == dic2.Count && !dic1.Except(dic2).Any();

关于c# - 在 C# 中测试字典之间的相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3804367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com