2012-11-24 38 views
2

如何通過在這種情況下使用lambda或linq來避免使用嵌套的foreach語句?現在已經很晚了,我似乎無法弄清楚如何訪問ErrorMessage屬性而不必恢復到嵌套的foreach語句。如果完全使用Lambda或Linq重寫代碼,那麼等效方法是什麼?如何通過在這種情況下使用lambda或linq來避免使用嵌套的foreach語句?

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; 
     } 

回答

4

你要使用SelectMany這個

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; 
    } 
+0

它編譯 - 謝謝:) – CarneyCode

0

是不是errors.Add(modelErrorCollection.SelectMany(x => x))

+0

請解釋一下:) – CarneyCode

相關問題