Linq - how to convert this code to linq
My Linq-fu is not good enough to translate the following into hopefully one or two lines.
var errors = new List<string>();
foreach (var key in ModelState.Keys)
{
errors.Add(ModelState[key].Errors.FirstOrDefault().ErrorMessage);
}
return Json(new { success = false, errors = erro开发者_Python百科rs });
The closes translation (which is unsafe because FirstOrDefault() could return null in which case your code would throw a null reference exception) would be:
return Json(new { success = false,
errors = ModelState.Values
.Select(ms => ms.Errors.FirstOrDefault().ErrorMessage)
.ToList() });
You could make it a bit safer using:
return Json(new {
success = false,
errors =
ModelState.Values
.Select(ms =>
{
var error = ms.Errors.FirstOrDefault();
return error == null ? error.ErrorMessage : "";
})
.ToList() });
The exact translation would be:
var errors = ModelState.Keys.Select(k => ModelState[k].Errors.First().ErrorMessage);
return Json(new { success = false, errors = errors.ToList() });
Provided ModelState is a Dictionary<TKey,TValue>
or similar, you could use the values directly:
var errors = ModelState.Values.Select(v => v.Errors.First().ErrorMessage);
return Json(new { success = false, errors = errors.ToList() });
return new Json(new
{
success = false,
errors = ModelState.Keys.Select(k => ModelState[key].Errors.First().ErrorMessage).ToList()
});
精彩评论