【问题标题】:How to use if condition on enumerable inside where clause [duplicate]如何在where子句中的可枚举上使用if条件[重复]
【发布时间】:2017-01-06 07:39:08
【问题描述】:

假设我有一个查询,我必须选择特定的产品。

我有一个名为 recipe 的类,它有无数关于使用的成分。

首先我想把所有没有被删除的收据都拿走,这很容易:

var recipes = context.Recipes.Where(a=> !a.Deleted);

现在我想通过 enumerable 来选择包含水的那些。会是这样的

recipes = recipes.Where(a => a.Ingridients.Where(b => b.Name == "Water"));

但问题就在这里。知道如何解决这个问题吗?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    在子查询中使用Any 而不是Where

    recipes = recipes.Where(a => a.Ingredients.Any(b => b.Name == "Water"));
    

    它将返回所有包含Water 作为成分之一的食谱。

    【讨论】:

    • 这很聪明。我发誓我试过类似的东西。再次感谢你!我会在 10 分钟内接受你的,因为那样我可以。
    猜你喜欢
    • 2021-09-13
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2015-08-27
    相关资源
    最近更新 更多