How do i convert a collection to count?
Where when a collection is passed the converter should be able to return the count for say the following collections,
Dictionary, ObservableCollection or List
right now i have the following but doesn’t work,
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((System.Collections.ICollection)value) != null ? ((System.Collections.ICollection)value).Count : 0;
}
If we define a “collection” as something that implements
ICollectionorICollection<T>then the Count property is available to tell us the number of elements in the collection if that is what we need to know.If we wish to calculate some value based upon ICollection.Count but modified in some way then we can create a Generic Method to calculate the value for us. For example, a generic method
Convert<T>could take anICollection<T> valueformal parameter. Such a function could be invoked using anything that implementsICollection<T>as an actual parameter.Because the compiler can infer the generic type argument we don’t need to explicitly specify the type argument when invoking the generic method (although we can do so if we want or need to).
For example…