score:2

Accepted answer

you won't be able to call a "local" method within your lambda expression. if this were a simple non-nested clause, it would be relatively simple - you'd just need to change this:

private func<testguy,int> getaveragefield(someenum somecondition)

to this:

private expression<func<testguy,int>> getaveragefield(someenum somecondition)

and then pass the result of the call into the relevant query method, e.g.

var results = query.select(getaveragefield(fieldtoaverageby));

in this case, however, you'll need to build the whole expression tree up for the select clause - the anonymous type creation expression, the extraction of the key, and the extraction of the average field part. it's not going to be fun, to be honest. in particular, by the time you've built up your expression tree, that's not going to be statically typed in the same way as a normal query expression would be, due to the inability to express the anonymous type in a declaration.

if you're using .net 4, dynamic typing may help you, although you'd pay the price of not having static typing any more, of course.

one option (horrible though it may be) would be try to use a sort of "template" of the anonymous type projection expression tree (e.g. always using a single property), and then build a copy of that expression tree, inserting the right expression instead. again, it's not going to be fun.

marc gravell may be able to help more on this - it does sound like the kind of thing which should be possible, but i'm at a loss as to how to do it elegantly at the moment.

score:0

eh? the parameter to queryable.average is not func<t, u>. it's expression<func<t, u>>

the way to do this is:

private expression<func<testguy,int>> getaverageexpr(someenum somecondition)
{
switch(somecondition)
{
case someenum.interesting:
  return tg => tg.interestingvalue;
case someenum.other:
  return tg => tg.othervalue;
}
throw new invalidoperationexception("not in my example!");
} 

followed by:

expression<func<testguy, int>> averageexpr = getaverageexpr(somecondition);
var bycity = testguys
  .groupby(c => c.city)
  .select(g => new { city = g.key, avg = g.average(averageexpr) });

Related Query

More Query from same tag