Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the count from ICollection<T> with an unknown T

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?

like image 674
Jonathan Allen Avatar asked Jan 18 '23 04:01

Jonathan Allen


1 Answers

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);
}
like image 68
Peter Oehlert Avatar answered Jan 29 '23 19:01

Peter Oehlert