Ortiga
Ortiga

Reputation: 8834

Why combined lambda expressions don't work in linq?

Delegates can be combined, so:

MethodInvoker del = delegate { Console.WriteLine("Delegate 1"); };
del += delegate { Console.WriteLine("Delegate 2"); };
del.Invoke();

Outputs:

Delegate 1 
Delegate 2

Since it calls both methods, I tried this to see if it would work:

Func<Person, bool> filters = person => person.Name.Contains("John");
filters += person => person.Age >= 18;

List<Person> persons = getPersons();

persons.Where(filters);

But it doesn't, only last is applied (in this case, person => person.Age >= 18).

My question is: Why not? Is it possible to implement this? (not that I would rewrite Linq's extension methods just to implement this, but would be cool if possible)

Note: I know that in LINQ to Objects, doing this would be similar, as execution is deferred:

persons.Where( x => x.Name.Contains( nameFilter )).Where( x => x.Age >= 18 );

But that's not what I'm interested in.

Upvotes: 0

Views: 183

Answers (2)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68747

The reason is that both filters are executed, but only the return value of the last delegate is used. That is how delegates work according to the specification. Like the comments say, I can't imagine how this would work differently. You're alluding that the results should be ANDed, but why can't they be ORed? What would happen if the results were strings?

Upvotes: 5

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112772

This works only with Action delegates, not with Func delegates, since a delegate call can only return one single result.

Upvotes: 1

Related Questions