I’m finding that I’m using LINQ more and more for simple problems that would otherwise have longwinded solutions. The brevity that LINQ offers is pretty powerful, and I appreciate that LINQ allows me to express what I want clearly and get the desired result.
One example today was when working with a custom calendar control that has a list of selected Days. A Day is also a custom control, and it has a Date property. I wanted to convert the list of selected Day controls into a list of selected dates.
The selection is a single range of dates, so my instinct was to find the minimum date from the list of selected days, find the maximum date from the list of selected days, then loop, adding each day’s date into a new list. Here’s what I came up with in about a minute:
Please note that DateTimeList is an alias to ObservableCollection<DateTime>
1: DateTimeList selectedDates = new DateTimeList();
2: DateTime start = new DateTime(_selectedDays.Min(day => day.Date.Ticks));
3: DateTime end = new DateTime(_selectedDays.Max(day => day.Date.Ticks));
4:
5:
6: while (start <= end)
7: {
8: selectedDates.Add(start);
9: start = start.AddDays(1);
10: }
That felt pretty good. I was able to just use Min and Max to find the bounds, and then loop over the range. But I had a feeling that LINQ could do me one better, and sure enough, it did:
1: DateTimeList selectedDates = new DateTimeList();
2: _selectedDays.ForEach(day => selectedDates.Add(day.Date));
I have a feeling there’s an even more succinct way to accomplish this task. Any suggestions?