The answer above from T I is great and saved me a lot of time. Posting an update here for anyone who may need this in method syntax, as I did, instead of query syntax.
var d = dates.GroupBy(date => date.Year)
.Select(year => new DateHierarchy
{
Level = 1,
Value = new DateTime(year.Key, 1, 1),
Children = year.GroupBy(date => date.Month)
.Select(month => new DateHierarchy
{
Level = 2,
Value = new DateTime(year.Key, month.Key, 1),
Children = month.GroupBy(date => date.Day)
.Select(day => new DateHierarchy
{
Level = 3,
Value = new DateTime(year.Key, month.Key, day.Key),
Children = null
})
})
});
I also needed to group items by the day of the week. To do this you can use CultureInfo.CurrentCulture.Calendar.GetWeekOfYear() as well as ISOWeek.ToDateTime() as follows.
var d = dates.GroupBy(date => date.Year)
.Select(year => new DateHierarchy
{
Level = 1,
Value = new DateTime(year.Key, 1, 1),
Children = year.GroupBy(date => date.Month)
.Select(month => new DateHierarchy
{
Level = 2,
Value = new DateTime(year.Key, month.Key, 1),
Children = month.GroupBy(date => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday))
.Select(week => new DateHierarchy
{
Level = 3,
Value = ISOWeek.ToDateTime(year.Key, week.Key, DayOfWeek.Sunday),
WeekOfYear = week.Key,
Children = week.GroupBy(date => date.Day)
.Select(day => new DateHierarchy
{
Level = 4,
Value = new DateTime(year.Key, month.Key, day.Key),
Children = null
})
})
})
});
Now to build and display that properly you will need to add a WeekOfYear property in your DateHierarchy class as well as add the appropriate DataTrigger in your xaml