I have two lists:
var myIds = new List<int>()
{
1, 2, 3
};
var yourIds = new List<int>()
{
2, 3, 4
};
The two lists can be combined into one like this:
myIds.Union(yourIds)
.Select(x => new
{
Id = x,
Mine = myIds.Contains(x),
Yours = yourIds.Contains(x)
});
The new list would look like this:
Id Mine Yours
---------------------
1 T F
2 T T
3 T T
4 F T
This works great when the lists contain elements. However, what if the lists have the possibility of being null. How could I handle the null lists?
If the lists could be null
, then you have to check for null
. You can also use null coalescing operator and if any of the list is null
then return an empty list (internally it will also check for null).
You can do:
(mIds ?? Enumerable.Empty<int>()).Union(yourIds ?? Enumerable.Empty<int>())
(thanks to @phoog comment)
But IMO, it is better to check against null
But if any of the list is empty, then you don't have to do any check, There will be no exception. Even if both the lists are empty , you will get an empty result back. The above code would return an empty list if any of the list is null
.
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