使用LINQ to SQL匹配特定日期的所有行

问题描述:

如何查找表中某一时间与特定日期匹配的所有行?使用LINQ to SQL匹配特定日期的所有行

Time的SQL数据类型为datetime

例如,假设你想从二零一四年九月二十零日所有行和表列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; 
+0

是你的时间字段'datetime'类型? – joym8 2014-09-25 00:19:55

+0

@ greatbear302是的,SQL数据类型是'datetime' – 2014-09-25 00:21:15

你可以尝试这样的事情之一:

// 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; 

var query = from t in SomeTable 
     where t.Time.Date == new DateTime(2014, 9, 20) 
     select t; 

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; 
} 

你可以使用扩展方法,使其多了几分读能:

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