LINQ connection with optional zero second parameter

I have two queries that return a collection of the same object, after completing these two queries, I want to combine 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 cannot return any results and will be null .

It seems that if I try to combine with two, if the second argument is null, it will throw an ArgumentNullException .

The obvious answer would be to simply execute .ToList() in the second query to see if it contains anything. The problem is that I am trying to use deferred execution and do not want to actually execute the query in the database at this point.

Is there any way around this?

Change - Solution

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

Basically, the actual query returned null as I was trying to make a list in a null list

Thanks for the help!

+4
source share
3 answers

results2 should return an empty list, not null when executing its request. The code you have should not cause any problems and should work perfectly in all cases, about simple cases that I can think of. Can you provide input that may cause the problem you are trying to solve?

+6
source

Can the following solve your problem?

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

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

 return results.Union(results2 ?? Enumerable.Empty<TResult>()); 
+3
source
 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 the results2, or simply return the first set of results.

0
source

Source: https://habr.com/ru/post/1341669/


All Articles