dpe*_*000 2 c# linq asp.net asp.net-mvc
我编写了以下代码以从ASP.Net MVC中的ViewData.Modelstate属性中引出异常以及引用该属性的字符串键.我认为应该可以用Linq表达式做到这一点,但它完全让我感到困惑.
var exceptions = new Dictionary<string, Exception>();
foreach (KeyValuePair<string, ModelState> propertyErrorsPair in ViewData.ModelState)
{
foreach (var error in propertyErrorsPair.Value.Errors)
{
if (error.Exception != null)
{
exceptions.Add(propertyErrorsPair.Key, error.Exception);
}
}
}
Run Code Online (Sandbox Code Playgroud)
那么Linq的做法是什么?我猜它可能与SelectMany有关,但正如我所说,我无法弄清楚如何实现这一目标.
谢谢
这是等效的LINQ表达式:
var result = ViewData.ModelState.SelectMany(x => x.Value.Errors
.Where(error => error.Exception != null)
.Select(error => new KeyValuePair<string, Exception>(x.Key, error.Exception)));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1170 次 |
| 最近记录: |