使用LINQ to SQL匹配特定日期的所有行
本文关键字:日期 to LINQ SQL 使用 | 更新日期: 2023-09-27 18:24:35
如何查找表中时间与特定日期匹配的所有行?
列Time
的SQL DataType为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;
你可以试试这样的东西:
// 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;
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;
}
var query = from t in SomeTable
where t.Time.Date == new DateTime(2014, 9, 20)
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));
(此解决方案发布在此处)