Crazy Linq: performing System.ComponentModel.DataAnnotations validation in a single statement

public static IEnumerable<ValidationResult> Validate(object component)
{
    return from descriptor in TypeDescriptor.GetProperties(component).Cast<PropertyDescriptor>()
            from validation in descriptor.Attributes.OfType<System.ComponentModel.DataAnnotations.ValidationAttribute>()
            where !validation.IsValid(descriptor.GetValue(component))
            select new ValidationResult(
                validation.ErrorMessage ?? string.Format(CultureInfo.CurrentUICulture, "{0} validation failed.", validation.GetType().Name),
                new[] { descriptor.Name });
}

...

Read full article

No Comments