Hilmi
Hilmi

Reputation: 3439

how to combine 2 Linq predicates -C#

i have the following function

public virtual ICollection<T> initData<T>(System.Data.Entity.DbSet<T> set, System.Linq.Expressions.Expression<Func<T, bool>> filter) where T : CModel<T>
        {
            var x = (from dc in set select dc);
            if (!this.db.valid)
            {
                System.Linq.Expressions.Expression<Func<T, bool>> active = a => a.active;
                filter = (Expression<Func<T, bool>>)Expression.Lambda(Expression.AndAlso(filter, active));
                x.Where(filter);

            }
            else
            {
                x.Where(filter);
            }
            return (ICollection<T>)x.ToList();
        }

when ever i try to combine the 2 predicates with AndAlso i throws an exception :

The binary operator AndAlso is not defined for the types 'System.Func`2[namespace.Models.MyClass,System.Boolean]' and 'System.Func`2[namespace.Models.MyClass,System.Boolean]'.

how can i combine these two conditions?

Upvotes: 1

Views: 2113

Answers (1)

Buh Buh
Buh Buh

Reputation: 7545

I think you are making life hard for yourself. You could just use the Where extension method multiple times like this:

public virtual ICollection<T> initData<T>(System.Data.Entity.DbSet<T> set, System.Linq.Expressions.Expression<Func<T, bool>> filter) where 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);
    }

    return x.ToList();
}

Note that in your code you used x.Where(filter);
This is useless because Where does not mutate x, so the result is basically discarded. To keep the result you need to assign it to something: x = x.Where(filter);.
This is the same idea as when you are working with strings.

 

Second answer:

There is a built in delegate called Predicate<T>. I think you might have more luck using this type than the Func<T, bool>, even though they both essentially have the same meaning. I think that be what the compiler error was trying to say.

Upvotes: 1

Related Questions