I'm trying to rewrite the following query as a separate statements:
var sql = Repository.Products.AsQueryable();
sql = sql.Where(x => x.Name == "aaaaa" || x.Name == "bbbbb");
If I do it like this:
sql = sql.Where(x => x.Name == "aaaaa");
sql = sql.Where(x => x.Name == "bbbbb");
then the resulting query is equal to:
sql = sql.Where(x => x.Name == "aaaaa" && x.Name == "bbbbb");
Is there any ideas how to do it the right way?
The right way... is that. I mean, you could write it as
sql.Where(x => x.Name == "aaaaa").Concat(sql.Where(x => x.Name == "bbbbb"));
but that's slower, unordered and looks weirder too. I don't know what you're looking for, because the way that you posted is the right way to do it.
However, it seems you want to build the expression dynamically (judging from your comment). If so, then you're looking for a PredicateBuilder
:
var predicate = PredicateBuilder.False<YourType>();
var search = new[] {"aaaaa", "bbbbb"};
foreach (string y in search)
{
string name = y;
predicate = predicate.Or(x => x.Name == name);
}
sql = sql.Where(predicate);
The code for PredicateBuilder
is here.
if you want to build you predicate based on come conditions use Predicate Builder
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