c# – 如何在“WHERE”条件下使用List编写LINQ to Entities查询
发布时间:2020-12-15 07:50:11 所属栏目:百科 来源:网络整理
导读:我想知道以列表作为条件来编写最有效的LINQ(编辑:实体)查询.这就是事情. 可以说我们有以下数据结构: public class Recipe { public int Id; public string Name; public ListIngredient IngredientList; } public class Ingredient { public int Id; 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(); 但是我收到以下错误:
解决方法
不要使用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(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 处理PostgreSQL Transactoin in Read Only Mode一例
- 详解vue-cli 构建项目 vue-cli请求后台接口 vue-cli使用axi
- 我可以确定任一个或语句中的哪个正则表达式匹配我的字符串吗
- 你如何在c#代码背后的通用控件(div)上设置innerhtml?
- 是否有人使用Address-Sanitizer(称为asan或-fsanitize =地址
- srping 两种配置方式:xml 和javaConfig
- Postgresql 学习笔记(1)
- postgreSQL的COPY (Bulk Data Transfer)
- 烟草行业MES系统控件通过Citrix XenApp发布导致IE Crash解决
- flex提供的基本表单验证