开发者

LINQ union with optional null second parameter

开发者 https://www.devze.com 2023-02-14 09:57 出处:网络
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.

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)
        se开发者_如何学Golect 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>());


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 (results2 != null || results2.Count() > 0) ? results.Union(results2) : results;

This will either return the union if there is something in results2, or just return the first result set.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号