I would like to compare lists of elements of a given type, to see which list is "bigger".
new BuiltInComparer<IEnumerable<int>>().Compare(
new[] {3,2,3},
new[] {1,2,3})
...would return 1
new BuiltInComparer<IEnumerable<int>>().Compare(
new[] {1,2,3},
new[] {1,2,4})
...would return -1 etc
Is there any such built in comparer?
I don't think there's anything built into the framework - and as Eric says, you haven't provided the comparison criteria. If you mean "compare element-wise in the natural way, and assume a 'missing' element is smaller than any present element" (i.e. a longer sequence beats a shorter subsequence if they're equal where possible) then something like this would do it:
public int SequenceCompare<T>(IEnumerable<T> source1, IEnumerable<T> source2)
{
// TODO: Parameter validation :)
// You could add an overload with this as a parameter
IComparer<T> elementComparer = Comparer<T>.Default;
using (IEnumerator<T> iterator1 = source1.GetEnumerator())
using (IEnumerator<T> iterator2 = source2.GetEnumerator())
{
while (true)
{
bool next1 = iterator1.MoveNext();
bool next2 = iterator2.MoveNext();
if (!next1 && !next2) // Both sequences finished
{
return 0;
}
if (!next1) // Only the first sequence has finished
{
return -1;
}
if (!next2) // Only the second sequence has finished
{
return 1;
}
// Both are still going, compare current elements
int comparison = elementComparer.Compare(iterator1.Current,
iterator2.Current);
// If elements are non-equal, we're done
if (comparison != 0)
{
return comparison;
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With