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

本文是小编为大家收集整理的关于Linq-如何在变量中存储 "where条件"?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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

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 函数,它可以工作,但这种方式不行.此代码返回空集.请问,你知道为什么吗?

推荐答案

您可能正在使用 LINQ to SQL 或类似的东西.

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

本文地址:https://www.itbaoku.cn/post/1556860.html

问题描述

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?

推荐答案

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.