c# – 如何在“WHERE”条件下使用List编写LINQ to Entities查询

c# – 如何在“WHERE”条件下使用List编写LINQ to Entities查询,第1张

概述我想知道以列表作为条件来编写最有效的LINQ(编辑:实体)查询.这就是事情. 可以说我们有以下数据结构: public class Recipe { public int Id; public string Name; public List<Ingredient> IngredientList; } public class Ingredient { publi 我想知道以列表作为条件来编写最有效的liNQ(编辑:实体)查询.这就是事情.

可以说我们有以下数据结构:

public class Recipe {   public int ID;   public string name;   public List<IngredIEnt> IngredIEntList; } public class IngredIEnt {   public int ID;   public string name; }

现在,我想做一个查询,搜索所有具有所有给定成分的食谱.

public List<Recipe> GetRecipesWhichHaveGivenIngredIEnts(List<IngredIEnts> ingredIEnts) {   List<Recipe> recipes;   using (DataContext context = new DataContext())   {    //efficIEnt liNQ query goes here    recipes = context.Recipes.Where(recipe => /*medaCode recipe.IngredIEntList.Contains(ingredIEnts) */).ToList();   }   return recipes; }

基本上这是如何确定给定集合是否是另一集合的子集的问题.

我尝试过以下查询(主要思想是使用Intersect *** 作):

List<Recipe> recipes = dataContext.Recipes.Include("IngredIEns").Where(rec => rec.IngredIEntList.Select(ingr => ingr.ID).Intersect(ingredIEnts.Select(sy =>  sy.ID)).Count() == ingredIEnts.Count).ToList();

但是我收到以下错误:

Unable to create a constant value of
type ‘Closure type’. Only primitive
types (‘such as Int32,String,and
GuID’) are supported in this context.

解决方法 不要使用List< IngredIEnt>对于你想要找到的成分;使用HashSet< IngredIEnt>和IsProperSubsetof方法,它接受一个集合作为其参数:
.Where(x => ingredIEnts.IsProperSubsetof(x.IngredIEntList))

除了作为O(n m) *** 作之外,还有一个额外的好处,就是可以在看到它时告诉你它正在做什么.

编辑

如果上述情况不明确:

public List<Recipe> GetRecipesWhichHaveGivenIngredIEnts(HashSet<IngredIEnt> ingredIEnts){   using (DataContext context = new DataContext())   {       return context.Recipes           .Where(x => ingredIEnts.IsProperSubsetof(x.IngredIEntList)             .ToList();   } }
总结

以上是内存溢出为你收集整理的c# – 如何在“WHERE”条件下使用List编写LINQ to Entities查询全部内容,希望文章能够帮你解决c# – 如何在“WHERE”条件下使用List编写LINQ to Entities查询所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1244271.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存