Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ union with optional null second parameter

Tags:

c#

linq

union

I have two queries which return a collection of the same kind of object, after these two queries are done, I want to union them.

var results = from t in All()
              where t.Blah.Contains(blahblah)
              select t;

var results2 = from t in All()
               where t.blah2.contains(blahblah)
               select t;

return results.Union(results2);

It is possible that the second query could return no results, and be null.

It seems like if I try and perform a union with the two, if the second argument is null it will throw an ArgumentNullException.

The obvious answer would be to just to perform .ToList() on the second query to see if it contains anything. The problem with this is I am trying to take advantage of deferred execution and dont want to actually perform the query on the database at this stage.

Is there any way around this?

Edit - Solution

var results2 = from t in All()
        where t.blah2!=null && t.blah2.Contains(blahblah)
        select t;

Basically, the actual query was returning null as I was trying to do a contains on a null list

Thanks for the help!

like image 553
Chris James Avatar asked Feb 28 '11 15:02

Chris James


2 Answers

results2 should return an empty list and not null when executing its query. The code you have should not cause any problems and should work just fine in all cases simple cases I can think of. Can you provide input which would cause the problem you are trying to solve?

like image 69
Nick Larsen Avatar answered Sep 22 '22 11:09

Nick Larsen


Would the following not solve your problem?

return from t in All()
       where t.Blah.Contains(blahblah) && t.Blah2.Contains(blahblah)
       select t;

However, if results and results2 need to remain separate and you want to combine them:

return results.Union(results2 ?? Enumerable.Empty<TResult>());
like image 40
user7116 Avatar answered Sep 23 '22 11:09

user7116