Skip to content

Instantly share code, notes, and snippets.

@ihorbond
Created July 1, 2020 21:16
Show Gist options
  • Save ihorbond/5e23e21216448132a84f3ad01004b4a5 to your computer and use it in GitHub Desktop.
Save ihorbond/5e23e21216448132a84f3ad01004b4a5 to your computer and use it in GitHub Desktop.
How to group items by day, week and year
IEnumerable<dynamic> GetGroup()
{
return settings.GroupBy switch
{
GroupByEnum.Day => listOfObjects.GroupBy(x => new DateTime(x.StartDate.Year, x.StartDate.Month, x.StartDate.Day))
.Select(x => new
{
Date = x.Key.ToString("d"),
Items = x
}),
GroupByEnum.Week => listOfObjects.GroupBy(x => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(x.StartDate, CalendarWeekRule.FirstDay, DayOfWeek.Monday))
.Select(x => new
{
Date = x.Count() == 1
? $"{x.First().StartDate.ToString("d")}"
: $"{x.Last().StartDate.ToString("d")} - { x.First().StartDate.ToString("d") }",
Items = x
}),
GroupByEnum.Month => listOfObjects.GroupBy(x => new DateTime(x.StartDate.Year, x.StartDate.Month, 1))
.Select(x => new
{
Date = x.Key.ToString("MMMM yyyy"),
Items = x
})
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment