Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat List<type> where lists can be null

Tags:

c#

I have three lists

List<Project> intProjects = ProjectRepo.GetAllInternalProjects();
List<Project> extProjects = ProjectRepo.GetAllExternalProjects();
List<Project> mgmProjects = ProjectRepo.GetAllManagementProjects();
List<Project> projects = intProjects.Concat(extProjects).Concat(mgmProjects).ToList();

If i have items in all of the lists it works fine, but i am receiving a null value exception when one of the lists is null.

Yes, i could do a

if (extProjects != null && mgmpProjects != null && intProjects != null)
    ...
else if (extProjects == null && mgmpProjects != null && intProjects != null
    ...

for all possible cases, but there must be a more effective way join lists even if they are null.

So my question is: How can i concat lists where lists can be null without getting an error?

like image 454
STORM Avatar asked Feb 04 '26 07:02

STORM


2 Answers

You could use an extension method like this

public static class EnumerableExtension
{
    public static IEnumerable<TSource> ConcatOrSkipNull<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
    {
        if (first == null)
           first = new List<TSource>();
        if (second == null)
            return first;
        return first.Concat(second);
    }
}

and rewrite your code then to:

 var projects = intProjects
                  .ConcatOrSkipNull(extProjects)
                  .ConcatOrSkipNull(mgmProjects)
                  .ToList();
like image 196
Ralf Bönning Avatar answered Feb 05 '26 20:02

Ralf Bönning


You could do something like this using the ?? operator:

List<Project> empty = new List<Project>();
List<Project> intProjects = ProjectRepo.GetAllInternalProjects() ?? empty;
List<Project> extProjects = ProjectRepo.GetAllExternalProjects() ?? empty;
List<Project> mgmProjects = ProjectRepo.GetAllManagementProjects() ?? empty;
List<Project> projects = intProjects.Concat(extProjects).Concat(mgmProjects).ToList();

?? Operator (C# Reference)

like image 20
Wagner DosAnjos Avatar answered Feb 05 '26 19:02

Wagner DosAnjos