views:

140

answers:

1

Hi, I wrote the following code to extract out the exceptions along with a string key referencing the property from the ViewData.Modelstate property in ASP.Net MVC. I think it should be possible to do this with a Linq expression but it utterly flummoxed me.

       var exceptions = new Dictionary<string, Exception>();
       foreach (KeyValuePair<string, ModelState> propertyErrorsPair in ViewData.ModelState)
       {
           foreach (var error in propertyErrorsPair.Value.Errors)
           {
               if (error.Exception != null)
               {
                   exceptions.Add(propertyErrorsPair.Key, error.Exception);
               }
           }
       }

So is there a Linq way of doing this? I'm guessing it might have something to do with SelectMany but as I say I couldn't quite work out how to achieve this.

Thanks

+3  A: 

This is the equivalent LINQ expression:

var result = ViewData.ModelState.SelectMany(x => x.Value.Errors
   .Where(error => error.Exception != null)
   .Select(error => new KeyValuePair<string, Exception>(x.Key, error.Exception)));
Mehrdad Afshari