Jonathan Kittell
Jonathan Kittell

Reputation: 7493

Match all rows on particular day using LINQ to SQL

How would you find all rows in a table that have a time matching a particular day?

The SQL DataType for the column Time is datetime.

For example, let's say you want all rows from 9/20/2014 and the table column Time looks like this...2014-09-20 17:02:05.903

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

Upvotes: 2

Views: 1626

Answers (4)

Bret
Bret

Reputation: 2291

You could use extension methods to make it a little more readable:

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

Now you can write:

dateToCheck.InRange(startDate, endDate)

or

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

(this solution was found posted here)

Upvotes: 1

joym8
joym8

Reputation: 4212

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

Upvotes: 2

Christos
Christos

Reputation: 53958

You could try something like this one:

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

Upvotes: 4

spender
spender

Reputation: 120390

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

Upvotes: 1

Related Questions