2

How do I avoid using nested foreach statements by using lambda or linq in this scenario? It's late and I cannot seem to figure out how to access the ErrorMessage property without having to revert to a nested foreach statement. What would be the equivalent method if the code was rewritten using wholly Lambda or Linq?

public static List<String> ExtractErrors(this ModelStateDictionary modelStateDictionary)
        {
            List<String> errors = new List<String>();

            var modelErrorCollection = (from modelState in modelStateDictionary.Values
                                        where modelState.Errors != null && modelState.Errors.Count > 0
                                        select modelState.Errors).ToList();

            foreach (var item in modelErrorCollection)
            {
                foreach (ModelError modelError in item)
                {
                    errors.Add(modelError.ErrorMessage);
                }
            }

            return errors;
        }
Phil C
  • 3,687
  • 4
  • 29
  • 51

2 Answers2

4

You'll want to use SelectMany for this

    public static List<String> ExtractErrors(this ModelStateDictionary modelStateDictionary)
    {
        var modelErrorCollection = (from modelState in modelStateDictionary.Values
                                    where modelState.Errors != null && modelState.Errors.Count > 0
                                    select modelState.Errors)
                                    .SelectMany(item=>item)
                                    .Select(modelError=>modelError.ErrorMessage)
                                    .ToList();
         return modelErrorCollection;
     }
juharr
  • 31,741
  • 4
  • 58
  • 93
0

Isn't it errors.Add(modelErrorCollection.SelectMany(x => x))?

Shaddix
  • 5,901
  • 8
  • 45
  • 86