Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two potentially null lists with linq [duplicate]

Tags:

c#

linq

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?

like image 633
navig8tr Avatar asked Sep 11 '14 13:09

navig8tr


1 Answers

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.

like image 192
Habib Avatar answered Oct 11 '22 03:10

Habib