题
我想在我的 Equals 方法中比较几个集合的内容。我有一本字典和一个 IList。有内置方法可以做到这一点吗?
编辑:我想比较两个字典和两个 IList,所以我认为相等的含义很清楚 - 如果两个字典包含映射到相同值的相同键,那么它们是相等的。
解决方案
通过使用指定的 IEqualityComparer(T) 比较两个序列的元素来确定两个序列是否相等。
您不能直接比较列表和字典,但可以将字典中的值列表与列表进行比较
其他提示
正如其他人所建议和指出的那样, SequenceEqual
是顺序敏感的。为了解决这个问题,您可以按键对字典进行排序(这是唯一的,因此排序始终稳定),然后使用 SequenceEqual
. 。以下表达式检查两个字典是否相等,无论其内部顺序如何:
dictionary1.OrderBy(kvp => kvp.Key).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key))
编辑: 正如 Jeppe Stig Nielsen 所指出的,某些物体具有 IComparer<T>
这与他们的不相容 IEqualityComparer<T>
, ,产生不正确的结果。当对此类对象使用键时,必须指定正确的 IComparer<T>
对于那些钥匙。例如,对于字符串键(出现此问题),您必须执行以下操作才能获得正确的结果:
dictionary1.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key, StringComparer.Ordinal))
看看 可枚举的.SequenceEqual 方法
var dictionary = new Dictionary<int, string>() {{1, "a"}, {2, "b"}};
var intList = new List<int> {1, 2};
var stringList = new List<string> {"a", "b"};
var test1 = dictionary.Keys.SequenceEqual(intList);
var test2 = dictionary.Values.SequenceEqual(stringList);
.NET 缺乏任何强大的工具来比较集合。我开发了一个简单的解决方案,您可以在下面的链接中找到:
http://robertbouillon.com/2010/04/29/comparing-collections-in-net/
这将执行相等比较,无论顺序如何:
var list1 = new[] { "Bill", "Bob", "Sally" };
var list2 = new[] { "Bob", "Bill", "Sally" };
bool isequal = list1.Compare(list2).IsSame;
这将检查是否添加/删除了项目:
var list1 = new[] { "Billy", "Bob" };
var list2 = new[] { "Bob", "Sally" };
var diff = list1.Compare(list2);
var onlyinlist1 = diff.Removed; //Billy
var onlyinlist2 = diff.Added; //Sally
var inbothlists = diff.Equal; //Bob
这将查看字典中的哪些项目发生了变化:
var original = new Dictionary<int, string>() { { 1, "a" }, { 2, "b" } };
var changed = new Dictionary<int, string>() { { 1, "aaa" }, { 2, "b" } };
var diff = original.Compare(changed, (x, y) => x.Value == y.Value, (x, y) => x.Value == y.Value);
foreach (var item in diff.Different)
Console.Write("{0} changed to {1}", item.Key.Value, item.Value.Value);
//Will output: a changed to aaa
我不知道 Enumerable.SequenceEqual 方法(你每天都会学到一些东西......),但我建议使用扩展方法;像这样的东西:
public static bool IsEqual(this List<int> InternalList, List<int> ExternalList)
{
if (InternalList.Count != ExternalList.Count)
{
return false;
}
else
{
for (int i = 0; i < InternalList.Count; i++)
{
if (InternalList[i] != ExternalList[i])
return false;
}
}
return true;
}
有趣的是,在花了 2 秒钟阅读 SequenceEqual 后,看起来 Microsoft 已经构建了我为您描述的函数。
这并不是直接回答你的问题,但是 MS 的 TestTools 和 NUnit 都提供了
CollectionAssert.AreEquivalent
这几乎可以满足你的需求。
要比较集合,您还可以使用 LINQ。 Enumerable.Intersect
返回所有相等的对。您可以这样比较两个字典:
(dict1.Count == dict2.Count) && dict1.Intersect(dict2).Count() == dict1.Count
需要第一个比较是因为 dict2
可以包含来自的所有键 dict1
和更多。
您还可以使用思考变化 Enumerable.Except
和 Enumerable.Union
导致类似的结果。但可用于确定集合之间的确切差异。
这个例子怎么样:
static void Main()
{
// Create a dictionary and add several elements to it.
var dict = new Dictionary<string, int>();
dict.Add("cat", 2);
dict.Add("dog", 3);
dict.Add("x", 4);
// Create another dictionary.
var dict2 = new Dictionary<string, int>();
dict2.Add("cat", 2);
dict2.Add("dog", 3);
dict2.Add("x", 4);
// Test for equality.
bool equal = false;
if (dict.Count == dict2.Count) // Require equal count.
{
equal = true;
foreach (var pair in dict)
{
int value;
if (dict2.TryGetValue(pair.Key, out value))
{
// Require value be equal.
if (value != pair.Value)
{
equal = false;
break;
}
}
else
{
// Require key be present.
equal = false;
break;
}
}
}
Console.WriteLine(equal);
}
对于有序集合(列表、数组)使用 SequenceEqual
供 HashSet 使用 SetEquals
对于字典你可以这样做:
namespace System.Collections.Generic {
public static class ExtensionMethods {
public static bool DictionaryEquals<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> d1, IReadOnlyDictionary<TKey, TValue> d2) {
if (object.ReferenceEquals(d1, d2)) return true;
if (d2 is null || d1.Count != d2.Count) return false;
foreach (var (d1key, d1value) in d1) {
if (!d2.TryGetValue(d1key, out TValue d2value)) return false;
if (!d1value.Equals(d2value)) return false;
}
return true;
}
}
}
(更优化的解决方案将使用排序,但这需要 IComparable<TValue>
)
不。集合框架没有任何平等的概念。如果你仔细想想,就没有办法比较非主观的收藏。例如,将 IList 与字典进行比较,如果所有键都在 IList 中,所有值都在 IList 中,或者两者都在 IList 中,它们会相等吗?如果不知道这两个集合的用途,就没有明显的方法来比较它们,因此通用的 equals 方法没有意义。
public bool CompareStringLists(List<string> list1, List<string> list2)
{
if (list1.Count != list2.Count) return false;
foreach(string item in list1)
{
if (!list2.Contains(item)) return false;
}
return true;
}
没有,没有,也可能不会,至少我相信是这样。背后的原因是集合相等可能是用户定义的行为。
集合中的元素不应该按特定的顺序排列,尽管它们确实有自然的排序,但这不是比较算法应该依赖的。假设您有两个集合:
{1, 2, 3, 4}
{4, 3, 2, 1}
它们是否相等?你一定知道,但我不知道你的观点是什么。
默认情况下,集合在概念上是无序的,直到算法提供排序规则。SQL Server 会引起您注意的同样的事情是,当您尝试进行分页时,它要求您提供排序规则:
还有另外两个合集:
{1, 2, 3, 4}
{1, 1, 1, 2, 2, 3, 4}
再说一遍,它们是否相等?你告诉我 ..
集合的元素重复性在不同的场景中发挥着作用,有些集合例如 Dictionary<TKey, TValue>
甚至不允许重复的元素。
我相信这些类型的平等是应用程序定义的,因此框架没有提供所有可能的实现。
嗯,一般情况下 Enumerable.SequenceEqual
已经足够好了,但在以下情况下会返回 false:
var a = new Dictionary<String, int> { { "2", 2 }, { "1", 1 }, };
var b = new Dictionary<String, int> { { "1", 1 }, { "2", 2 }, };
Debug.Print("{0}", a.SequenceEqual(b)); // false
我读了一些这样的问题的答案(你可能 谷歌 对于他们)以及我一般会使用的内容:
public static class CollectionExtensions {
public static bool Represents<T>(this IEnumerable<T> first, IEnumerable<T> second) {
if(object.ReferenceEquals(first, second)) {
return true;
}
if(first is IOrderedEnumerable<T> && second is IOrderedEnumerable<T>) {
return Enumerable.SequenceEqual(first, second);
}
if(first is ICollection<T> && second is ICollection<T>) {
if(first.Count()!=second.Count()) {
return false;
}
}
first=first.OrderBy(x => x.GetHashCode());
second=second.OrderBy(x => x.GetHashCode());
return CollectionExtensions.Represents(first, second);
}
}
这意味着一个集合在其元素中代表另一个集合,包括重复次数,而不考虑原始顺序。实施的一些注意事项:
GetHashCode()
只是为了排序而不是为了平等;我认为在这种情况下就足够了Count()
不会真正枚举集合,直接落入属性实现ICollection<T>.Count
如果参考文献相同,那就是鲍里斯