I am currently in a situation where i need to compare two ICollection, and validate
a) whether the second contains the same items as the first one,
b) and if there is an extra element, ensure that it can be vali dated using a validation method.
The way I am currently doing this is by
a boolean as this
bool hasBaseSequence = x.SequenceEqual(y.ToList().GetRange(0, x.Count),Comparer)
Is there a neater way of doing this rather than having to use GetRange()
to specify the range in which the SequenceEqual
and then define another range for the new entry in the list stating the the new entry that needs to be validated?
It feels a bit like a hackish way of handling this?
What you have isn't so bad!
If the collections are large you might suffer from repeated iteration, therefore you could use a method like the following to provide the same validation functionality you have described while only iterating the collections at most once. Not even that if there is an invalid item!
public static bool ValidateWithBaseSequence<T>(
IEnumerable<T> baseSequence,
IEnumerable<T> newSequence,
IEqualityComparer<T> equalityComparer,
Func<T, bool> newItemValidator)
{
using var baseEnumerator = baseSequence.GetEnumerator();
using var newEnumerator = newSequence.GetEnumerator();
while (baseEnumerator.MoveNext())
{
if (newEnumerator.MoveNext())
{
if (!equalityComparer.Equals(
baseEnumerator.Current,
newEnumerator.Current))
{
return false;
}
}
else
{
throw new InvalidOperationException(
"New sequence is shorter than base sequence.");
}
}
while (newEnumerator.MoveNext())
{
if (!newItemValidator(newEnumerator.Current))
{
return false;
}
}
return true;
}
Usage:
var isValid = ValidateWithBaseSequence(x, y, Comparer, item => vaidationFunction(item));