【问题标题】:Match all rows on particular day using LINQ to SQL使用 LINQ to SQL 匹配特定日期的所有行
【发布时间】:2014-09-25 00:08:30
【问题描述】:

如何查找表中时间与特定日期匹配的所有行?

Time 列的 SQL 数据类型是 datetime

例如,假设您想要 2014 年 9 月 20 日的所有行,而表列 Time 看起来像这样...2014-09-20 17:02:05.903

var query = from t in SomeTable
            where t.Time // don't know what goes here
            select t;

【问题讨论】:

  • 你的时间栏是datetime类型吗?
  • @greatbear302 是的,SQL 数据类型是datetime

标签: c# linq


【解决方案1】:

你可以试试这样的:

// Define your startDate. In our case it would be 9/20/2014 00:00:00
DateTime startDate = new DateTime(2014,09,20);

// Define your endDate. In our case it would be 9/21/2014 00:00:00
DateTime endDate = startDate.AddDays(1);

// Get all the rows of SomeTable, whose Time is between startDate and endDate.
var query = from t in SomeTable
            where t.Time>= startDate and t.Time<=endDate
            select t;

【讨论】:

    【解决方案2】:
    void DoSomethingWithSomeTable(int day, int month, int year)
    {
        var query = from t in SomeTable
                    where t.Time.Date.Equals(new DateTime(year, month, day))
                    select t;
    }
    

    【讨论】:

      【解决方案3】:
       var query = from t in SomeTable
              where t.Time.Date == new DateTime(2014, 9, 20)
              select t;
      

      【讨论】:

        【解决方案4】:

        您可以使用扩展方法使其更具可读性:

        public static class DateTimeExtensions
        {
            public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate)
            {
                return dateToCheck >= startDate && dateToCheck < endDate;
            }
        }
        

        现在你可以写:

        dateToCheck.InRange(startDate, endDate)
        

        var start = new DateTime(2014, 9, 20);
        dateToCheck.InRange(start, start.AddDays(1));
        

        (this solution was found posted here)

        【讨论】:

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