I have structure ifs:
if()
{
query = query.Where(....)
}
if()
{
query = query.Where(....)
}
as they do to these two tests work together, and do not overwrite each other?
I have structure ifs:
if()
{
query = query.Where(....)
}
if()
{
query = query.Where(....)
}
as they do to these two tests work together, and do not overwrite each other?
as they do to these two tests work together, and do not overwrite each other?
Your code will (depending on the outcome in the if()
s) chain the queries.
The final result will be that all .Where(...)
s are applied to the source.
You should be able to chain your query expression:
query = query.Where(....).Where(....);
If you want to have some flexibility in predicate creation, I'd suggest LinqKit. With this library you can build your Where
clause dynamically, to get, for example:
if(condition)
{
predicate.And(something);
}
if(otherCondition)
{
predicate.Or(somethingElse);
}
var result = source.Where(predicate);
It has open source code, very easy to understand, basing on Expression
class, which is actually used by Linq.
It's also worth noticing, that the result is computed only when it's needed - so it's a good solution to create a condition for Linq2SQL.
var flg1 = cond1 == null? true : cond1;
var flg2 = cond2 == null? true : cond2;
var result = query.Where(flg1 && flg2)
You also can use the DynamicQuery library. Then you can use like
query.Where("field1=1 and field2=2");