Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine .Select from two LINQ expressions into one?

Tags:

c#

linq

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?

like image 383
Angela Avatar asked Dec 12 '25 17:12

Angela


2 Answers

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;
}
like image 98
Kirk Broadhurst Avatar answered Dec 15 '25 19:12

Kirk Broadhurst


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;
}
like image 21
StuartLC Avatar answered Dec 15 '25 21:12

StuartLC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!