linq中基于参数值的倍数 [英] multiple where in linq based on parameters value
问题描述
我想在linq中有多个where子句,但是其中只有一个应该执行,我正在尝试如下操作:
I want to have multiple where clauses in linq but out of them only one should execute, i was trying something like this:
public JsonResult GetPost(int? id, int? tagid, DateTime? date)
{
var ret = from data in db.Posts.Include(x => x.Tags)
.Include(x => x.Neighbourhood)
.Where((x => x.NeighbourhoodId == id) || (y => y.PostedDate == date) || third condition).ToList()
但是在y后面加点之后,我无法在第二和第三条件那里放becoz,我看不到任何选择.
but i was unable to put second and third condition there becoz after putting dot after y, i cant see any options.
现在,在这三个参数中,只有一个参数将具有值,而另外两个参数将具有null,因此,它仅应检查具有值的参数.
Now, out of these three, only one parameter would have value and other two would have null so, it should checks for parameter only with value.
我应该这样写查询吗,这是正确的方法吗?
should i write query like this, is it correct way:
if (id != null)
{
//whole query here
}
else if (tagid != null)
{
//whole query here
}
else (date != null)
{
//whole query here
}
这是执行此操作的最佳方法,还是可能的其他方法.任何建议都要提前很多.
Is it the best way to do this or something else is possible. many many thnks in advance for any suggestion.
推荐答案
像这样吗?
var ret = from data in db.Posts.Include(x => x.Tags)
.Include(x => x.Neighbourhood)
.Where(x => x.NeighbourhoodId == (id ?? x.NeighbourhoodId) &&
x.<condition> == (tagid ?? x.<condition>) &&
x.PostedDate == (date ?? x.PostedDate).ToList();
或者像这样:
var ret = from data in db.Posts.Include(x => x.Tags)
.Include(x => x.Neighbourhood)
.Where(x => id.HasValue ? x.NeighbourhoodId == id :
tagid.HasValue ? x.<condition> == tagid :
x.PostedDate == date).ToList();
这篇关于linq中基于参数值的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!