Alex Rivera | Logout

How to use System.Linq.Expressions.Expression to filter based on children?

Asked 2012-04-27T19:44:43.320
12

I have a filter that I use across many methods:

Expression<Func<Child, bool>> filter = child => child.Status == 1;

(actually is more complex than that)

And I have to do the following

return db.Parents.Where(parent => parent.Status == 1 &&
                                  parent.Child.Status == 1);

where the condition is the same as in the filter above.

I want to reuse the filter in this method. But I don't know how. I tried

return db.Parents.Where(parent => parent.Status == 1 &&
                                  filter(parent.Child));

but an Expression can't be used as a method

Edit
Report

1 Answer

0

Could you just use the expression as a function instead?

Instead of:

Expression<Func<Child, bool>> filter = child => child.Status == 1;

Use that same expression as a generic function this way:

Func<Child, bool> filter = child => child.Status == 1;

Then you will be able to use the function in just the same way you were trying to use an expression:

return db.Parents.Where(parent => parent.Status == 1 &&
                                  filter(parent.Child));

Edit: I misunderstood the question. This is a bad answer. 6+ years out, I'm still getting comments to the effect that this doesn't work. I'm not sure, from a hygiene perspective, if it would be better to just delete the answer, or add this edit and let the answer stand as an example of something that decidedly doesn't work. I'm open to advisement on that.

answered 2012-05-09T14:30:47.223

Your Answer