问题
Edited to be clearer.
If for example I have this 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
};
and later in the method I want to add an OR to it, e.g.
// 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");
}
This effectively makes my query...
var query = from org in Organisations
where org.DisableOrganisation == false &&
org.DisableReports == false &&
org.Frequency == "M"
select new
{
OrganisationId = org.OrganisationId
};
but I want to make it...
var query = from org in Organisations
where (org.DisableOrganisation == false &&
org.DisableReports == false) ||
org.Frequency == "M"
select new
{
OrganisationId = org.OrganisationId
};
How do I go about making this an OR instead of an AND ?
P.S. Cannot use PredicateBuilder as it is essentially LinqKit which has a dependency of EntityFramework (≥ 6.0.2), I'm stuck using EF 4.3.1
SOLVED: Thanks to D Stanley (To be honest I had used this form of solution before, I simply forgot about it).
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
};
回答1:
You can't do it by chaining - you'll have to use some sort of expression builder, or just build that in your original 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
};
回答2:
To combine conditions with OR instead of AND, use the PredicateBuilder:
predicate = predicate.Or(p => p.Description.Contains (temp));
return dataContext.Products.Where(predicate);
来源:https://stackoverflow.com/questions/32866123/chaining-building-linq-query-with-an-or-instead-of-and