InB*_*een 5 c# ienumerable equality
好的,我需要测试两个IEnumerable<T>是否相等.元素的顺序很重要,这意味着:
{1, 2, 4, 1, 3} and {1, 2, 1, 3, 4} should not be equal.
Run Code Online (Sandbox Code Playgroud)
我在这个网站上看到了一些解答如何解决这个问题的答案linq:例如,这里
问题是我必须反复测试相当大的集合(数千个元素)的相等性,这些集合很可能不相等,因此性能是一个要考虑的因素.我看到它的linq方式,所提到的答案(Count或Except)中显示的所有方法都需要,如果我没有弄错的话,迭代整个集合,在一般情况下是不必要的.
我提出了这个代码,它运行得相当好(我认为)并且足够快.我想知道我是否缺少一些明显的内置方法(如果可能的话,我不想在这里重新发明轮子.)
public static bool IsEqualTo<T>(this IEnumerable<T> inner, IEnumerable<T> other) where T: IEquatable<T>
{
if (inner == null)
throw new ArgumentNullException();
if (object.ReferenceEquals(inner, other))
return true;
if (object.ReferenceEquals(other, null))
return false;
using (var innerEnumerator = inner.GetEnumerator())
using (var otherEnumerator = other.GetEnumerator())
{
while (innerEnumerator.MoveNext())
{
if (!otherEnumerator.MoveNext() || !innerEnumerator.Current.Equals(otherEnumerator.Current))
return false;
}
return !otherEnumerator.MoveNext();
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,当没有找到元素时,您希望将评估短路.
IEnumerable.SequenceEqual(MSDN)已经这样做了; 通过以下实现证明:http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs(806行)
当订单很重要时,您应该能够编写一个简单的while循环:
int i = 0;
int aCount = a.Count(); //Use `IList` so you can use the property for efficiency
int bCount = b.Count(); //Use `IList` so you can use the property for efficiency
if (aCount != bCount)
return false;
while (a.ElementAt(i) == b.ElementAt(i))
i++;
return i == aCount;
Run Code Online (Sandbox Code Playgroud)
你的功能基本上是一样的,并且可以正常工作.
| 归档时间: |
|
| 查看次数: |
107 次 |
| 最近记录: |