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?
You could use 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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With