tags:

views:

55

answers:

1

I have a view model like so that is created from my validator.

public class ViewModel
{
    public KeyValuePair<int, RuleType> Foo { get; set; }
    public KeyValuePair<string, RuleType> Bar { get; set; }
}

My real view model has 20+ field. Once my data is validated a generic list of type ViewModel is then returned to my MVC view and processed into a report. However, a feature request has come up where users wish to only see models with errors and warning, excluding valid entities. RuleType is a enumerator. A model is valid if all values of the key pair are RuleType.Success.

Is it possible to loop through each model and checking the RuleType without manually having to check every property? My GetAllModelsWithErrors() function would return a list of invalid models. I believe reflection could be a solution however I'm not sure if it's a good solution.

+2  A: 

Try this:

    private IEnumerable<ViewModel> GetInvalidModels(ViewModel[] viewModels)
    {
        return 
            from viewModel in viewModels 
            from prop in typeof(ViewModel).GetProperties() 
            let ruleType = ((KeyValuePair<object, RuleType>)prop.GetValue(viewModel, null)).Value 
            where ruleType != RuleType.Success 
            select viewModel;
    }
danijels
The `let ruleType` line is throwing an invalid exception when I use `ToList()` on my results. Should I be doing something different if some of my KeyValuePair values have nullable types?
Mike
As you said yourself, "A model is valid if all values of the key pair are RuleType.Success". Therefore, my query is based on the assumption that your values in KeyValuePairs are always of RuleType type which is an Enum and thus not nullable.
danijels
You're completely right. Thank you. :)
Mike