如何将两个LINQ表达式的.Select合并为一个?

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

1
“Combine”是什么意思?您想要一个枚举,其中包含所有错误消息,然后是所有异常吗?还是一个具有“Error”和“Exception”属性的对象枚举?或者是一个字符串枚举,其中每个字符串都是错误消息和异常消息的连接? - Amith George
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;
}

你可以在第二个例子中使用数组.SelectMany(error => new [] { error.Exception, error.ErrorString } - nemesv
@Kirk - 我尝试了Union方法,但是它给了我两个错误:错误4 实例参数:无法从'System.Collections.Generic.IEnumerable<System.Exception>'转换为'System.Linq.IQueryable<string>'和'System.Collections.Generic.IEnumerable<System.Exception>'不包含'Union'的定义,最佳扩展方法重载'System.Linq.Queryable.Union<TSource>(System.Linq.IQueryable<TSource>, System.Collections.Generic.IEnumerable<TSource>)'有一些无效的参数。 - Angela
1
@Angela - 请注意,在您的原始帖子中,error.Exception 是一个异常。要转换为字符串,您可以使用带有堆栈跟踪的 .ToString(),或仅使用消息的 .Message - StuartLC
@nonnb - 谢谢。抱歉,我想问题出在我身上,因为我的问题没有提到它是一个异常而不是字符串。 - Angela
@Angela,我认为它是一个字符串,因为在你的问题中它是一个字符串。 - Kirk Broadhurst

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

如果您没有实际执行联合操作的理由,那么使用“Join”可能比使用“Union”更好。 - BAF

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接