3

I would like to replace the lambda expression in the following code

var idQuery = Query<ApiStatisticsAggregatedStats>.EQ(t => t.Api, id);

with a func. Hovering over the statement it says the declaration is

Func<ApiStatisticsAggregatedStats, string>

The following code gives an error though,

Func<ApiStatisticsAggregatedStats, string> idFunc = x => x.Api
var idQuery = Query<ApiStatisticsAggregatedStats>.EQ(idFunc, id);

Error:

The best overloaded method match for Query<ApiStatisticsAggregatedStats>.EQ<string>(Expression<Func<ApiStatisticsAggregatedStats, IEnumerable<string>>>, string) has some invalid arguments.

Where did that IEnumerable come from? What am I doing wrong?

2
  • @marc_s Thanks for cleaning up the post. However, that error section you did truncated the message since the "less-than" characters were removed. Commented Mar 25, 2014 at 16:34
  • Sorry 'bout that - fixed. Commented Mar 25, 2014 at 16:39

1 Answer 1

5

Query providers, like mongoDB query provider, use expression trees instead of delegates. That's why you have to declare your variable as

Expression<Func<ApiStatisticsAggregatedStats, string>> idFunc = x => x.Api

You can still assign a lambda expression to Expression<Func<...>> variable, because compiler can transform your lambda into proper method calls from Expression class during compilation.

When a lambda expression is assigned to a variable of type Expression<TDelegate>, the compiler emits code to build an expression tree that represents the lambda expression.

However, it works for single-line lambdas only.

The C# and Visual Basic compilers can generate expression trees only from expression lambdas (or single-line lambdas). It cannot parse statement lambdas (or multi-line lambdas).

If you'd try doing following:

Expression<Func<ApiStatisticsAggregatedStats, string>> idFunc = x => { return x.Api };

(notice { and }) you'd get compile error saying compiler is not able to transform multi-line lambda into expression tree.

Bot quotes come from Expression Trees (C# and Visual Basic).

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Worked wonders. I had tried to assign the Func to an Expression, which compiled but failed at runtime. Guess it's time to properly read through the section on expression trees in C# in Depth.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.