Linq - How to store "where condition" in a variable

Is it possible to store the Where clause in this linq expression in a 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
                                    });

The condition is 100% right. If I write the condition f => f.barcode == namedirectly to the Where function, this works, but it doesnโ€™t. This code returns an empty set. Please do you know why?

+1
source share
2 answers

You are probably using LINQ to SQL or something similar.

You must change your variable to Expression<Func<NutritionValues, bool>>; this will allow the request provider to analyze your condition.

+2
source

Oh my, there can be a lot of things. First enter conditionhow Expression<Func<NutritionValues, bool>>. This will allow your query provider to parse it correctly.

-, (name), ( , , foods , ), , . . .

0

All Articles