使用OR而不是AND链接/构建LINQ查询
编辑得更清楚。
例如,我有这个IQueryable:
DateTime theDate = new DateTime(2015, 09, 30); var query = from org in Organisations where org.DisableOrganisation == false && org.DisableReports == false select new { OrganisationId = org.OrganisationId };
然后在方法中我想向它添加一个OR,例如
// Check to see if the date is the last day of the month. if (theDate.AddDays(1).Day == 1) { // The following statement introduces an AND but I want to make this an OR. query = query.Where(x => x.Frequency == "M"); }
这有效地使我的查询……
var query = from org in Organisations where org.DisableOrganisation == false && org.DisableReports == false && org.Frequency == "M" select new { OrganisationId = org.OrganisationId };
但我想成功……
var query = from org in Organisations where (org.DisableOrganisation == false && org.DisableReports == false) || org.Frequency == "M" select new { OrganisationId = org.OrganisationId };
我该怎么做这个OR而不是AND?
PS不能使用PredicateBuilder,因为它本质上是LinqKit,它具有EntityFramework(≥6.0.2)的依赖性,我坚持使用EF 4.3.1
解决:感谢D Stanley(说实话我之前使用过这种forms的解决方案,我只是忘了它)。
DateTime theDate = new DateTime(2015, 09, 30); bool isEndOfMonth = theDate.AddDays(1).Day == 1; var query = from org in Organisations where (org.DisableOrganisation == false && org.DisableReports == false) || (isEndOfMonth && pr.ProfileType == "L" && pr.Frequency == "M") select new { OrganisationId = org.OrganisationId };
你不能通过链接来做 – 你必须使用某种表达式构建器,或者只是在原始filter中构建它:
var day = theDate.AddDays(1).Day; var query = from org in Organisations where (org.DisableOrganisation == false && org.DisableReports == false) || (day == 1 && org.ProfileType == "L" && org.Frequency == "M") select new { OrganisationId = org.OrganisationId };
要将条件与OR而不是AND组合,请使用PredicateBuilder:
上述就是C#学习教程:使用OR而不是AND链接/构建LINQ查询分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
predicate = predicate.Or(p => p.Description.Contains (temp)); return dataContext.Products.Where(predicate);
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1012283.html