Maz H
Maz H

Reputation: 151

Passing in Func<T, bool> to LINQ Where

Hi I have a simple repository layer with a method as below:

public Questionnaire GetQuestionnaire(Expression<Func<Question, bool>> predicateFunc)
    {
        return new Questionnaire
        {
            Title = "Geography Questions",
            Questions = GetQuestionnaireData().Where(predicateFunc.Compile()).ToList()
        };
    }

This is querying against an IEnumerable collection in memory named 'GetQuestionnaireData()'

However from the above Method signature I am using an Expression> predicateFunc. Which I then use in the where clause of the linq query by predicateFunc.Compile.

My question is this: Is it possible to pass in a Func Delegate to a linq where clause without using an Expression and delegate.compile?

Perhaps this may be possible using a @IEnumerable.Select(somePredicateFunc) ?

Upvotes: 3

Views: 1956

Answers (2)

Ra&#250;l Ota&#241;o
Ra&#250;l Ota&#241;o

Reputation: 4770

Yes you can. Maybe is that you haven't tested before, or there is some another specification in your question that you are not showing there. Look this code sample:

    static void Main(string[] args)
    {

        Test(i => i > 3);
    }

    static void Test(Func<int, bool> f)
    {
        IEnumerable<int> k = new [] {5, 4, 3, 22,1};
        foreach (var i in k.Where(f))
            Console.WriteLine(i);
    }

Hope it helps.

Upvotes: 2

nvoigt
nvoigt

Reputation: 77364

Sure, just drop the expression:

public Questionnaire GetQuestionnaire(Func<Question, bool> predicateFunc)
{
    return new Questionnaire
    {
        Title = "Geography Questions",
        Questions = GetQuestionnaireData().Where(predicateFunc).ToList()
    };
}

Upvotes: 5

Related Questions