Amit Kumar
Amit Kumar

Reputation: 1397

Linq c# use between on time span

I have two field in data base named "StartTime" and "EndTime"

I have saved a record as

StartTime           EndTime
05:00:00.0000000    06:00:00.0000000

I want to display an error message if another record is inserted at the same or between 05:00:00.0000000 to 06:00:00.0000000

This means no matter what the start and end times are it should not occur between 05 to 06.

04 to 06 - Show error
04:30 to 06 - Show error
05:00 to 07 - Show error

How I achieve this using linq?

This is my current attempt, which does not generate the proper results:

string _timepicker_start = collection["timepicker_start"];
string _timepicker_end = collection["timepicker_end"];
TimeSpan _end = new TimeSpan(Convert.ToInt16(_timepicker_end.Split(':')[0])
    ,  Convert.ToInt16(_timepicker_end.Split(':')[1]), 00);
TimeSpan _start = new TimeSpan(Convert.ToInt16(_timepicker_start.Split(':')[0])
    , Convert.ToInt16(_timepicker_start.Split(':')[1]), 00);

var _schedule = _db.Classes
                 .Where(c => c.StartTime <= _start && c.EndTime >= _end)
                .FirstOrDefault(); 

if (_schedule != null)
{
    // Show message already have record.. 
}

It does not work properly please suggest me.

Upvotes: 1

Views: 1772

Answers (2)

Amit Kumar
Amit Kumar

Reputation: 1397

Thanks to stack over flow:

I have got my solution as:

            var _schedule = _db.Classes
             .Where(c => (c.StartTime >= _start || c.StartTime <_end)&& c.EndTime > _end)
            .FirstOrDefault(); 

Thanks for quick response and help !!!

Upvotes: 0

Rawling
Rawling

Reputation: 50104

You want c => c.EndTime > _start && c.StartTime < _end in your Where.

(Add equality if you don't want the items to be able to "touch" at either end.)

This assumes you're validating StartTime <= EndTime for everything.

Upvotes: 3

Related Questions