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

时间:2014-09-25 00:08:30

标签: c# linq

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

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;

4 个答案:

答案 0 :(得分:3)

你可以试试这样的东西:

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

答案 1 :(得分: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;
}

答案 2 :(得分:1)

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

答案 3 :(得分:1)

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

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