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!
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?
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>());
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