Broge
Broge

Reputation: 73

Query range of data linq c#

I have a calendar in my website and users can create events of one or more days.
So, in my Calendar table I set two fields Start(Datetime) and End(Datetime).

I want to do a query with a specific date range like from 08/01/2017 to 08/31/2017.
Now, how can I take all the events that are in this range?

I have to take:


Is it possible to do a single query or i have to do three different query?

I hope I explained myself, otherwise ask me...

Upvotes: 0

Views: 995

Answers (3)

Fildor
Fildor

Reputation: 16104

I would say it should be enough to test for event.End >= range.Start && event.Start <= range.End

       0 1 2 3 4 5 6 7 8 9
Range        |-----|
Evt1   |-|                   evt.End < range.Start => false
Evt2                 |-|     evt.Start > range.End => false
Evt3     |-----------|       => true
Evt4     |-------|           => true
Evt5             |-----|     => true
Evt6           |-|           => true

Upvotes: 1

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

Your requirements can be boiled down to the facts that:

  • the event starts before the end of the range and
  • the event ends after the start of the range

(the "and" is important, otherwise events totally outside the range will match, too).

So, this should work:

DateTime startRange = new DateTime(2017, 08, 01);
DateTime endRange   = new DateTime(2017, 08, 32);

var events = db.Events.Where(e => e.Start <= rangeEnd && e.End >= rangeStart);

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460138

DateTime startRange = new DateTime(2017, 08, 01);
DateTime endRange   = new DateTime(2017, 08, 32);

var events = db.Events
   .Where(e => e.Start >= startRange && startRange <= e.End && e.End >= endRange
            || e.Start <= startRange && e.End >= endRange
            || e.Start <= startRange && endRange >= e.Start && e.End <= endRange);

Is this sufficient?

Upvotes: 2

Related Questions