没有,现在没有,也可能没有,至少我会这么认为。背后的原因是集合相等可能是用户定义的行为。
集合中的元素不应该按特定顺序排列,尽管它们自然有顺序,但这不是比较算法应该依赖的。假设您有两个集合:
{1, 2, 3, 4}
{4, 3, 2, 1}
它们是否相等?你一定知道,但我不知道你的观点是什么。
默认情况下,集合在概念上是无序的,直到算法提供排序规则。 SQL server 会引起你注意的是,当你尝试进行分页时,它需要你提供排序规则:
https://docs.microsoft.com/en-US/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-2017
还有两个系列:
{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
我阅读了一些此类问题的答案(您可以为他们google)以及我一般会使用什么:
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);
}
}
这意味着一个集合在其元素中代表另一个集合,包括重复次数,而不考虑原始顺序。实现的一些注意事项: