【问题标题】:linq where statement with OR带有 OR 的 linq where 语句
【发布时间】:2011-03-03 19:19:11
【问题描述】:

我正在使用 linq-to-sql 进行这样的查询:

public static List<MyModel> GetData(int TheUserID, DateTime TheDate)

using (MyDataContext TheDC = new MyDataContext())
{
   var TheOutput = from a in TheDC.MyTable
     where a.UserID == TheUserID
     (where a.Date1.Month == TheDate.Month && where a.Date1.Year == TheDate.Year)
     OR
     (where a.Date2.Month == TheDate.Month && where a.Date2.Year == TheDate.Year)
     group a by a.Date1.Date AND by a.Date2.Date into daygroups
     select new MyModel{...};

如何编写此代码以使 OR 和 AND 语句起作用?我试过放一个||和 && 就位,但它不起作用,我被困在这个查询上。

基本上,它应该返回一个月内的天数列表,并且在 MyModel 中,我确实很重要。例如,在一个列中,我计算在给定日期设置的约会数量,在另一列中,我计算在同一天参加的约会数量。 Date1 是指设置约会的日期,Date2 是指参加约会的日期。例如,在 2011 年 3 月 3 日,我设置了 4 个约会(这些约会的日期 1 是 2011 年 3 月 11 日),并且它们被设置为未来的不同日期(日期 2)。在同一天(这次是 3 月 3 日是 Date2),我还参加了过去在其他日期安排的其他几个约会。

感谢您的任何建议。

【问题讨论】:

    标签: c# linq linq-to-sql


    【解决方案1】:
    using (MyDataContext TheDC = new MylDataContext())
    {
       var TheOutput = from a in TheDC.MyTable
         where a.UserID == TheUserID &&   
         (a.Date1.Month == TheDate.Month && a.Date1.Year == TheDate.Year)
         ||
         ( a.Date2.Month == TheDate.Month && a.Date2.Year == TheDate.Year)
         group a by a.Date1.Date AND by a.Date2.Date into daygroups
         select new MyModel{...};
    

    尝试删除 4 个额外的“where”并将 OR 更改为 ||。

    【讨论】:

    • 我试过了,它几乎到处都是红色的。我还在努力。
    • 好的,我明白你关于删除额外的 where 语句的意思。现在红色下划线是 group 语句所在的位置。如何使用 AND 语句进行分组?
    • “分组依据”不正确。它只包含单词“AND”。如果您想按多个事物分组,请使用“new {a = .., b=...}”并按匿名类型分组。
    • 我明白了!!!!您只需将 AND 替换为 == 即可:将 a 按 a.Date1.Date == a.Date2.Date 分组到 daygroups
    • 我相信 Group By 没有 and ......所以它就像“按 a.Date1.Date, a.Date2.Date 将 a 分组到 daygroups” - 我没有虽然做了很多分组,但我需要检查一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多