Linq - How to store “where condition” in variable

我的梦境 提交于 2019-12-24 06:47:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!