Linq-如何存储"where condition"在变量中 [英] Linq - How to store "where condition" in variable

查看:95
本文介绍了Linq-如何存储"where condition"在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在此linq语句中的变量中存储Where条件?

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
                                    });

条件是100%正确.如果我将条件f => f.barcode == name直接写到Where函数中,则它可以工作,但这种方式不行.此代码返回空集.拜托,你知道为什么吗?

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?

推荐答案

您可能正在使用LINQ to SQL或类似的工具.

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

您应该将变量更改为Expression<Func<NutritionValues, bool>>;这将使查询提供程序可以解析您的条件.

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

这篇关于Linq-如何存储"where condition"在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆