问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/4818748/linq-how-to-store-where-condition-in-variable