我如何组合。从两个LINQ表达式中选择一个?

时间:2012-08-26 08:04:09

标签: c# linq

我有以下代码段。

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值?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;
}