I have this custom validation attribute for validating a collection. I need to adapt this to work with IEnumerable. I tried making the attribute a generic, but you can’t have a generic attribute.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class CollectionHasElements : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public override bool IsValid(object value)
{
if (value != null && value is IList)
{
return ((IList)value).Count > 0;
}
return false;
}
}
I’m having trouble casting it to an IEnumerable so that I can check its count() or any().
Any ideas?
Try this
or, since C# 7.0 with pattern matching:
Note: Testing for
ICollection.Countis more efficient than getting an enumerator and beginning to enumerate the enumerator. Therefore I try to use theCountproperty whenever possible. However, the second test would work alone, since a collection always implementsIEnumerable.The inheritance hierarchy goes like this:
IEnumerable > ICollection > IList.IListimplementsICollectionandICollectionimplementsIEnumerable. ThereforeIEnumerablewill work for any well designed type of collection or enumeration but notIList. For instanceDictionary<K,V>does not implementIListbutICollectionand therefore alsoIEnumeration.The .NET naming conventions say that an attribute class name should always end in "Attribute". Therefore your class should be named
CollectionHasElementsAttribute. When applying the attribute you can drop the "Attribute" part.