Thursday, 15 March 2012

asp.net mvc - how to combine 2 Linq predicates -C# -



asp.net mvc - how to combine 2 Linq predicates -C# -

i have next function

public virtual icollection<t> initdata<t>(system.data.entity.dbset<t> set, system.linq.expressions.expression<func<t, bool>> filter) t : cmodel<t> { var x = (from dc in set select dc); if (!this.db.valid) { system.linq.expressions.expression<func<t, bool>> active = => a.active; filter = (expression<func<t, bool>>)expression.lambda(expression.andalso(filter, active)); x.where(filter); } else { x.where(filter); } homecoming (icollection<t>)x.tolist(); }

when ever seek combine 2 predicates andalso throws exception :

the binary operator andalso not defined types 'system.func`2[namespace.models.myclass,system.boolean]' , 'system.func`2[namespace.models.myclass,system.boolean]'.

how can combine these 2 conditions?

i think making life hard yourself. utilize extension method multiple times this:

public virtual icollection<t> initdata<t>(system.data.entity.dbset<t> set, system.linq.expressions.expression<func<t, bool>> filter) t : cmodel<t> { var x = (from dc in set select dc); x = set.where(filter); if (!this.db.valid) { x = x.where(a => a.active); } homecoming x.tolist(); }

note in code used x.where(filter); useless because not mutate x, result discarded. maintain result need assign something: x = x.where(filter);. same thought when working strings.

 

second answer:

there built in delegate called predicate<t>. think might have more luck using type func<t, bool>, though both have same meaning. think compiler error trying say.

asp.net-mvc linq linq-to-sql

No comments:

Post a Comment