I am trying to do union of three lists of type T in C# , but when any of them is null it throws null reference exception

250 views Asked by At

Here is my code snippet:

var joinedList = List1.List.Where(x => x != null)
.Union(List2.List.Where(x=> x!= null).Union(List3.List.Where(x => x!= null))).ToList();
1

There are 1 answers

2
Paul Linton On BEST ANSWER
var joinedList = new List<T>();
if (List1.List != null) joinedList = joinedList.Union(List1.List.Where(x=>x!=null);
if (List2.List != null) joinedList = joinedList.Union(List2.List.Where(x=>x!=null);
if (List3.List != null) joinedList = joinedList.Union(List3.List.Where(x=>x!=null);