3

我有以下代码片段。

protected IEnumerable<string> GetErrorsFromModelState()
{
    var errors =  ModelState.SelectMany(x => x.Value.Errors
            .Select(error => error.ErrorMessage));
    return errors;
}

protected IEnumerable<string> GetErrorsFromModelState()
{
    var exceptions = ModelState.SelectMany(x => x.Value.Errors
            .Select(error => error.Exception));
    return exceptions;
}

有没有办法可以将这两者结合起来,以便 GetErrorsFromModelState 将返回所有 ErrorMessage 和 Exception 值?

4

2 回答 2

6

你可以使用Union

protected IEnumerable<string> GetErrorsFromModelState()
{
    var exceptions = ModelState.SelectMany(x => x.Value.Errors
        .Select(error => error.Exception));

    var errors =  ModelState.SelectMany(x => x.Value.Errors
        .Select(error => error.ErrorMessage));

    return exceptions.Union(errors);
}

或者您可以将它们选择到一个集合中

protected IEnumerable<string> GetErrorsFromModelState()
{
    var items = ModelState.SelectMany(x => x.Value.Errors
        .SelectMany(error => 
                          {
                              var e = new List<string>();
                              e.Add(error.Exception);
                              e.Add(error.ErrorString);
                              return e;
                          }));

    return items;
}
于 2012-08-26T08:16:49.437 回答
3

当然 - 使用Enumerable.Union扩展方法

protected IEnumerable<string> GetErrorsAndExceptionsFromModelState()
{
    var errors = ModelState
                    .SelectMany(x => x.Value.Errors.Select(error => error.ErrorMessage)
                    .Union(x.Value.Errors.Select(error => error.Exception.Message)));
    return errors;
}
于 2012-08-26T08:09:08.740 回答