c# - How to get a date range from a list of fromdate & todate to compare with another date -


i have collection of dates below,

var datelist = new list<dateprev> {     new dateprev{ fromdate=new datetime(2014,10,1), todate=new datetime(2015,3,1)},     new dateprev{ fromdate=new datetime(2013,2,1), todate=new datetime(2013,10,1)},     new dateprev{ fromdate=new datetime(2010,2,1), todate=new datetime(2011,10,1)} }; 

this list serves lookup list. have search data below,

var newdate = new dateprev { fromdate = new datetime(2015, 2, 1), todate = new datetime(2017, 5, 1) }; 

i want search inside datelist collection find out whether supplied newdate can inserted inside datelist proper date range. supplied date list's date earlier todate of first row of datelist, should not allow insert.

if understand question correctly, you're looking way check if 2 "date-spans" overlap.

i, myself, had such problem, , solution rather easy.

given 2 dates defined as:

  • date astart , aend
  • date b bstart , bend

you can determine if overlap if: !(aend < bstart || astart > bend)

as such, can write following code:

class dateprev {     public datetime fromdate { get; set; }     public datetime todate { get; set; }      public static bool overlap(dateprev datea, dateprev dateb)     {         return !(datea.todate < dateb.fromdate || datea.fromdate > dateb.todate);     } }  (...)          var newdate = new dateprev(); //specify ,          if (!datelist.any(d => dateprev.overlap(d, newdate)))             datelist.add(newdate); 

the code assumes dateprev contains "sane" values - i.e. todate > fromdate. also, may want tweak condition depending on if treat / end dates inclusive or exclusive (changing < or > <= or => needed).


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - How to Hide Date Menu from Datepicker in yii2 -