Linq and creating queries on the fly

B

Bram

One of the great things about SQL is that it's exceedingly easy to
create queries on the fly. I'm trying to accomplish the same using
linq but I'm running into problems when I'm trying to do the
following:

void PopulateOldPeople() {
Populate(p => p.BirthDate < DateTime.Now.AddYears(-65));
}

void PopulateWomen() {
Populate(p => p.Sex = Sex.Woman);
}

void Populate(Func<Person, bool> filter) {
var people = from Person p in DB.Persons
where filter(p)
select p;
foreach(Person p in people) {
// Add item to list box
}
}

This code throws an exception in the foreach loop, when the expression
in 'people' is actually expanded. I'm pretty certain that the reason
is the 'where' clause expects an Expression<Func<T0, R>> and not a
Func<T0, R>. How do I plug an expression into the where clause?
Replacing Func<Person, bool> with Expression<Func<Person, bool>>
causes a compile error.

Kind regards,
Bram Fokke
 
J

Jon Skeet [C# MVP]

Bram said:
One of the great things about SQL is that it's exceedingly easy to
create queries on the fly. I'm trying to accomplish the same using
linq but I'm running into problems when I'm trying to do the
following:

void PopulateOldPeople() {
Populate(p => p.BirthDate < DateTime.Now.AddYears(-65));
}

void PopulateWomen() {
Populate(p => p.Sex = Sex.Woman);
}

void Populate(Func<Person, bool> filter) {
var people = from Person p in DB.Persons
where filter(p)
select p;
foreach(Person p in people) {
// Add item to list box
}
}

This code throws an exception in the foreach loop, when the expression
in 'people' is actually expanded. I'm pretty certain that the reason
is the 'where' clause expects an Expression<Func<T0, R>> and not a
Func<T0, R>. How do I plug an expression into the where clause?
Replacing Func<Person, bool> with Expression<Func<Person, bool>>
causes a compile error.

Try this code instead:

void PopulateOldPeople()
{
Populate(p => p.BirthDate < DateTime.Now.AddYears(-65));
}

void PopulateWomen()
{
Populate(p => p.Sex = Sex.Woman);
}

void Populate(Expression<Func<Person, bool>> filter)
{
var people = DB.Persons.Where(filter);

foreach(Person p in people)
{
// Add item to list box
}
}

Query expressions are nice, but they're not really appropriate in this
case. Just calling the extension method manually is simpler here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top