c# - Find missing date in List<DateTime> and insert that date on the right index -


say have list following dates.

list<datetime> datelist = new list<datetime>(); datelist.add(new datetime(2002, 01, 01)); datelist.add(new datetime(2002, 01, 02)); datelist.add(new datetime(2002, 01, 03)); datelist.add(new datetime(2002, 01, 04)); datelist.add(new datetime(2002, 01, 06)); datelist.add(new datetime(2002, 01, 08)); 

how can iterate through datelist, find datetimes missing (2002-01-05 , 2002-01-07), create datetimes , add them datelist on correct index?

you can use following approach determines min- , max-dates , timespan difference , generates list:

datetime min = datelist.min(); datetime max = datelist.max(); timespan diff = max - min; datelist = enumerable.range(0, diff.days + 1).select(d => min.adddays(d)).tolist(); 

you need use diff.days + 1 include end-date.

if can't use linq whatever reason use for-loop , list.insert, have use list.sort beforehand if aren't sure whether list sorted or not:

datelist.sort(); if (datelist.count > 1) {     (int = 0; < datelist.count - 1; i++)     {         datetime currrent = datelist[i].date;         datetime next = datelist[i + 1].date;         datetime expected = currrent.adddays(1);         if (next != expected)         {             datelist.insert(++i, expected);         }     } } 

you see how more readable linq version is.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -