I was wondering whether it's possible 开发者_运维技巧to add/remove a where clause from a linq expression/ query operators.
Eg :-
var qry = from e in emp where(e => e.salary > 5000) select e;
Is it possible to remove where expression at a later stage?
Thanks in advance :)
Yes, it is possible, but you need to implement an ExpressionVisitor
class to evaluate the composite expression and change it according to your needs. Unless you are doing something relatively complex there is probably a better way to accomplish what you want.
you can only adjust your filtering as far as i know
for example if are trying to delete based on condition e.salary > 5000 , they you should try something like
var diffQry = from e in emp where(e => e.salary <= 5000) select e;
If you want to programmatically add and remove where clauses you can use query operators.
var query = emp.Select(x => x);
if (someCondition)
query = query.Where(x => x.Price > 50);
You need to expand on your question a little more.
If qry
is an IQueryable<T>
-- for example, a LINQ-to-SQL or LINQ-to-Entities query -- then it should be possible to analyse the underlying expression tree and build a new one excluding the Where
clause.
If qry
is a plain IEnumerable<T>
-- for example, a LINQ-to-Objects query -- then this can't be done since there will be no expression tree to analyse.
I think WHERE
clause is required if there is a conditional query. Otherwise (if no condition) you can use:
var qry = from e in emp select e;
精彩评论