TI 的上述答案很棒,为我节省了很多时间。像我一样,为任何可能需要方法语法而不是查询语法的人发布更新。
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
})
})
});
我还需要按星期几对项目进行分组。为此,您可以使用CultureInfo.CurrentCulture.Calendar.GetWeekOfYear()以及ISOWeek.ToDateTime(),如下所示。
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
})
})
})
});
现在要正确构建和显示,您需要在DateHierarchy类中添加WeekOfYear属性,并在 xaml中添加适当的DataTrigger