Errol Paleracio
Errol Paleracio

Reputation: 634

How to check if date_start1 and date_end1 overlaps with date_start2 and date_end2 using linq

I have a database that contains these columns:

event_start, event_end. 

How do I check if start and endoverlaps with event_start and event_end stored in the database. Here is my code I am using now:

public static bool IsAvailable(DateTime, start, DateTime, end)
{
    var query = from evnt in dbContext.events
                select evnt;
    foreach (var q in query)
    {
        if (start < q.event_end || end > q.event_start)
        {
            return false;
        }
    } 
    return true;
}

Upvotes: 1

Views: 60

Answers (3)

Yu Yenkan
Yu Yenkan

Reputation: 765

you can use this query to check is that any record clash with a specific range of date.

var query = (from evnt in dbContext.events
            where evnt.event_end >= start
            || evnt.event_start <= end 
            select evnt ).FirstOrDefault();

if(query != null){
    //it is overlap
}

If any record found by this query, there is at least one event overlap with your given date.

Edited changed from evnt.event_start >= end to <= and evnt.event_end <= start to >=

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66449

It's not enough that the start date is before the event end date - the end date has to be after the event start date too. Replace || with &&.

Also, you can replace the loop with a call to Any():

return !dbContext.events.Any(q => start < q.event_end && end > q.event_start); 

Upvotes: 2

Maarten
Maarten

Reputation: 22945

Add a Where to your query.

var data = dbContext.Events
    .Where(q => !(start < q.event_end || end > q.event_start))
    .ToList();

Upvotes: 1

Related Questions