[英]How can I combine .Select from two LINQ expressions into one?
I have the following code snippets. 我有以下代码片段。
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;
}
Is there a way that I could combine these two so that GetErrorsFromModelState will return all the ErrorMessage and Exception values? 有没有办法可以将这两者结合起来,以便GetErrorsFromModelState将返回所有ErrorMessage和Exception值?
You could use Union
你可以使用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);
}
or you could select them into a single collection 或者您可以将它们选择为单个集合
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;
}
Sure - use the Enumerable.Union extension method 当然 - 使用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.