c# - What is the best way to convert a list of dates so it displays in groups if it contains consecutive days? -
i have list of dates
var list = new list<datetime>(); list.add(new datetime(2014, 1,1); list.add(new datetime(2014, 1,2); list.add(new datetime(2014, 1,3); list.add(new datetime(2014, 1,5); list.add(new datetime(2014, 1,6); list.add(new datetime(2014, 1,11);
and dates consecutive. want group consecutive dates , render on ui as:
"jan 1-3, 2015; jan 5-6, 2015; jan 11, 2015"
what correct way lis t transformation? without . this:
var display = string.join(";", list.select(r=>r.tostring("dd-mmm-yyyy"));
void main() { var list = new list<datetime>(); list.add(new datetime(2014, 1, 1)); list.add(new datetime(2014, 1, 2)); list.add(new datetime(2014, 1, 3)); list.add(new datetime(2014, 1, 5)); list.add(new datetime(2014, 1, 6)); list.add(new datetime(2014, 1, 11)); string output = string.join("; ", getranges(list).select(formatrange)); console.writeline(output); // jan 1–3, 2014; jan 5–6, 2014; jan 11, 2014 } private string formatrange (daterange range) { if (range.start.year != range.end.year) return range.start.tostring("mmm d, yyyy") + " – " + range.end.tostring("mmm d, yyyy"); else if (range.start.month != range.end.month) return range.start.tostring("mmm d") + " – " + range.end.tostring("mmm d, yyyy"); else if (range.start.day != range.end.day) return range.start.tostring("mmm d") + "–" + range.end.tostring("d, yyyy"); else return range.start.tostring("mmm d, yyyy"); } private list<daterange> getranges (ienumerable<datetime> dates) { list<daterange> ranges = new list<daterange>(); daterange current = null; datetime? previous = null; foreach (datetime date in dates) { if (!previous.hasvalue) current = new daterange() { start = date }; else if ((date - previous.value).days > 1) { current.end = previous.value; ranges.add(current); current = new daterange() { start = date }; } previous = date; } if (previous.hasvalue) { current.end = previous.value; ranges.add(current); } return ranges; } public class daterange { public datetime start { get; set; } public datetime end { get; set; } }
Comments
Post a Comment