【问题标题】:multiple where in linq based on parameters value [duplicate]基于参数值的linq中的多个位置[重复]
【发布时间】:2016-02-04 13:43:36
【问题描述】:

我想在 linq 中有多个 where 子句,但其中只有一个应该执行,我正在尝试这样的事情:

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 之后放点后,我看不到任何选项。

现在,在这三个参数中,只有一个参数有值,另外两个有空值,所以它应该只检查有值的参数。

我应该这样写查询,是不是正确的方式:

if (id != null)
{
//whole query here
}
else if (tagid != null)
{
//whole query here
}
else (date != null)
{
//whole query here
}

这是执行此操作的最佳方法还是可能的其他方法。任何建议提前很多很多。

【问题讨论】:

  • @krillgar 抱歉,我错过了这个,但是关于这个话题的答案太多了,所以我有点迷路了,没有回答这个问题

标签: c# asp.net-mvc linq


【解决方案1】:

这样的?

            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();

【讨论】:

  • 工作就像一个魅力正是我在寻找我的 +1 @Julia
【解决方案2】:

另一种选择是更动态地构建您的查询。我认为这也使您的代码更具可读性,并且如果需要,您的条件可以更复杂(例如,在循环内构建查询或其他内容)。您可以将其与任何其他运算符一起使用,例如 Include 等。一旦您的查询构建完成,您可以调用 ToList()

var ret = db.Posts.Include(x => x.Tags).Include(x => x.Neighbourhood);
if (id != null)
{
    ret = ret.Where((x => x.NeighbourhoodId == id);
}
else
{
    ...
}
var result = ret.ToList();

【讨论】:

    【解决方案3】:

    您可以使用以下内容:

    var ret = from data in db.Posts.Include(x => x.Tags)
                     .Include(x => x.Neighbourhood)
                     .Where(x => id == null || x.NeighbourhoodId == id) 
                     .Where(x => date == null || y.PostedDate == date) 
                     .ToList();
    

    如果参数为空,where 子句返回序列的每个元素。如果它不为空,它只返回匹配的元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      相关资源
      最近更新 更多