c# - Algorithm for testing inequality of ordered large collections -
c# - Algorithm for testing inequality of ordered large collections -
ok, need test if 2 ienumerable<t>
equal. order of elements is important, means that:
{1, 2, 4, 1, 3} , {1, 2, 1, 3, 4} should not equal.
i've seen few answers on site explaining how linq
: example, here
the problem have repeatedly test equality of pretty big collections (thousands of elements) have high probability of not beingness equal, performance factor bear in mind. way see it, linq
methods shown in referred reply (count
or except
) need to, if i'm not mistaken, iterate through whole collection in general case not necessary.
i came code, works reasonably (i think) , fast enough. wondering if i'm missing obvious built in way of doing (i don't want reinvent wheel here if possible.)
public static bool isequalto<t>(this ienumerable<t> inner, ienumerable<t> other) t: iequatable<t> { if (inner == null) throw new argumentnullexception(); if (object.referenceequals(inner, other)) homecoming true; if (object.referenceequals(other, null)) homecoming false; using (var innerenumerator = inner.getenumerator()) using (var otherenumerator = other.getenumerator()) { while (innerenumerator.movenext()) { if (!otherenumerator.movenext() || !innerenumerator.current.equals(otherenumerator.current)) homecoming false; } homecoming !otherenumerator.movenext(); } }
basically looking short-circuit evaluation when element isn't found.
ienumerable.sequenceequal
(msdn) this; proved out implementation in: http://referencesource.microsoft.com/#system.core/system/linq/enumerable.cs (line 806)
when order important, should able write simple while loop:
int = 0; int acount = a.count(); //use `ilist` can utilize property efficiency int bcount = b.count(); //use `ilist` can utilize property efficiency if (acount != bcount) homecoming false; while (a.elementat(i) == b.elementat(i)) i++; homecoming == acount;
your function same thing, , work fine.
c# ienumerable equality
Comments
Post a Comment