I have two IEnumerable variables, both can be null. I need to merge them into a single list. Here is direct 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 in less lines of code to do this?
Just check for null and assign Enumerable.Empty
if it is null. This can be done in one step with the null coalescing operator ??
var ienumerable1 = GetEnumerable1() ?? Enumerable.Empty<WhateverType>();
var ienumerable2 = GetEnumerable2() ?? Enumerable.Empty<WhateverType>();
return ienumerable1.Union(ienumerable2);
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