Question

I am trying to store a linq express in a variable, But it gives me this compile time error

Emebeded Statement can not be a declaration or labled stateme

I found how to assign a linq expression to a variable from this question of stackoverflow Lambdaexpression of Linq-query in a variable

But When i try to implement it, I get the below error , Can someone help me ?

The code I tried

 if (dtpFrom.DateTime != null) 
           Func<BAL.Receipt , DateTime? > expr = receipt => receipt.Date ;
Was it helpful?

Solution

It's because that snippet of code isn't valid C#. this other StackOverflow answer explains why. To summarize that answer, the C# specification states that the body of an if statement must be an embedded-statement, which does not include statements that are variable declarations.

To get your code to stop causing that error, you can try just throwing brackets around the if statement body:

if (dtpFrom.DateTime != null) 
{
    Func<BAL.Receipt , DateTime? > expr = receipt => receipt.Date ;
}

Although this won't do much of anything, since you're just storing that lambda in a temporary variable of type Func<,> which only has scope in the if statement. You'll either have to use it within the if state body or store it somewhere else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top