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?
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();
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)
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