【问题标题】:LINQ where not between a date rangeLINQ 不在日期范围之间
【发布时间】:2014-05-01 22:27:49
【问题描述】:

我有以下 linq 查询:

public static int GetContributions(PERSON person, DateTime startDate, DateTime endDate)
    {
        using (var db = new TestEntities())
        {
            var creditsSum = (from u in db.PERSON_SOCIAL_INSURANCE_CONTRIBUTIONS
                              where u.StartDate >= startDate
                              where u.EndDate <= endDate
                              where (u.PersonId == person.Id)
                              select (int?)u.NumOfContributions).Sum() ?? 0;

            return creditsSum;
        }
    }

我想创建一个类似的方法来返回不属于提供的开始日期和结束日期之间的贡献数。所以基本上它会返回所有不在 startDate 和 endDate 值之间的条目。

有什么帮助吗?

【问题讨论】:

  • 你能解释一下fall这个词吗?没有与给定区间或完全包含的交集?
  • 我的意思是没有给定区间的交集

标签: c# .net linq linq-to-sql linq-to-entities


【解决方案1】:

将所有条件放在一起,用括号括起来,然后取反。

var creditsSum = (from u in db.PERSON_SOCIAL_INSURANCE_CONTRIBUTIONS
                          where !(u.StartDate >= startDate
                          && u.EndDate <= endDate)
                          where (u.PersonId == person.Id)
                          select (int?)u.NumOfContributions).Sum() ?? 0;

【讨论】:

  • 交叉点可能会出现。
【解决方案2】:

然后改变你的条件:

var creditsSum = (from u in db.PERSON_SOCIAL_INSURANCE_CONTRIBUTIONS
                  where (u.StartDate > endDate || u.EndDate < startDate) &&
                        u.PersonId == person.Id
                  select (int?)u.NumOfContributions).Sum() ?? 0;

你不需要那么多 where 语句,只需使用 AND 运算符即可。

【讨论】:

  • 如果我决定 u.StartDate &lt; u.EndDatestartDate &lt; endDate(这几乎是真的),你的 where 子句就是 false
  • @HamletHakobyan 你是对的,更新了条件。
【解决方案3】:

您的Where 子句可能如下所示:

b.PERSON_SOCIAL_INSURANCE_CONTRIBUTIONS
 .Where(
           (c => c.StartDate > endDate || c.EndDate < startDate)
           && u.PersonId == person.Id
       )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多