Here is my code so far:
//TODO: Look for a way of handling ICollection<T>
if (value is ICollection)
{
return CreateResult(validationContext, ((ICollection)value).Count);
}
if (value is IEnumerable)
{
var enumerator = ((IEnumerable)value).GetEnumerator();
try
{
var count = 0;
while (enumerator.MoveNext())
count++;
return CreateResult(validationContext, count);
}
finally
{
if (enumerator is IDisposable)
((IDisposable)enumerator).Dispose();
}
}
Is there a good way of getting the Count
out of ICollection<T>
without resorting to iterating over the collection?
Without having the closed type of ICollection<T>
, you'd have to resort to reflection to call the Count property.
if (typeof(ICollection<>) == value.GenericTypeDefinition()) {
var countProp = value.GetType().GetProperty("Count");
var count = (int)countProp.GetValue(value, null);
}
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