2

its possible to store Where condition in this linq statement in variable?

Func<NutritionValues, bool> condition;
if (isBarcode)
   condition = f => f.barcode == name;
else
   condition = f => f.food == name;


var foods = context.NutritionValues.Where(condition).
                                    Select(f => new SerializableFood
                                    {
                                         Name = f.food,
                                         Calories = f.energy_kcal,
                                         Carbohydrates = f.carbohydrates,
                                         Fats = f.fats,
                                         Proteins = f.protiens
                                    });

Condition is 100% right. If I write condition f => f.barcode == name directly into the Where function it works, but this way not. This code return empty set. Please, do you know why?

2 Answers2

3

You're probably using LINQ to SQL or something similar.

You should change your variable to an Expression<Func<NutritionValues, bool>>; this will allow the query provider to parse your condition.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Oh my, there could be a lot going on here. First, you should type condition as an Expression<Func<NutritionValues, bool>>. This will let your query provider parse it properly.

Second, you're capturing a variable (name) and if you modify the value of that variable between the time of capture and the time that the query is actually executed (note that the query is not executed until you iterate over foods, it has not been executed in any of the code that you've shown us), you will see different results than you might expect. For more on this topic, see Closing over the loop variable considered harmful.

jason
  • 236,483
  • 35
  • 423
  • 525
  • I don't want to task your's minds with more code. Buts it would be better to expose more code in this case. I know about lazy evaluation so i don't modify captured variable before execution. Thank you for your help. – Karlvonbahnhof Jan 28 '11 at 11:14