Merging two IEnumerables in an elegant way
I have two IEnumerable variables, both can be null. I need to combine them into one list. Here's a straight forward approach.
var ienumerable1 = GetEnumerable1();
var ienumerable2 = GetEnumerable2();
if(ienumerable1 != null){
if(ienumerable2 != null){
return ienumerable1.Union(ienumerable2);
}
return ienumerable1;
}
else{
return ienumerable2;
}
Is there a more elegant way for smaller lines of code?
+3
source to share
2 answers
Just check for null and assign Enumerable.Empty
if it is null. This can be done in one step using the null coalescing operator ??
var ienumerable1 = GetEnumerable1() ?? Enumerable.Empty<WhateverType>();
var ienumerable2 = GetEnumerable2() ?? Enumerable.Empty<WhateverType>();
return ienumerable1.Union(ienumerable2);
+14
source to share