I assumed you are using DynamicNode class which will give the following solution:
var nestedGroups = from p in newsOverview.Descendants("duhubCalendarItem").Items.OrderByDescending(x => DateTime.Parse(x.GetPropertyValue("date")))
group p by DateTime.Parse(p.GetPropertyValue("date")).Year into yg
select new {
Year = yg.Key,
Months = from o in yg
group o by DateTime.Parse(o.GetPropertyValue("date")).Month into mg
select new {
Month = mg.Key,
Items = mg.Select(x => x)
}
};
Which can be accessed like so:
foreach (var groupedYear in nestedGroups) {
int year = groupedYear.Year;
foreach (var groupedMonth in groupedYear.Months) {
int month = groupedMonth.Month;
foreach (var newsItem in groupedMonth.Items) {
string name = newsItem.Name;
}
}
}
Do not forget to add the using at the top of the razorscript:
This has been super-handy lothar - thanks for posting it :)
I had to modify slightly, but it now works fantastically well:
int sourceNodeId = 1234;
var sourceNode = Umbraco.TypedContent(sourceNodeId);
var nestedGroups = from p in sourceNode.Descendants().Where(x => x.DocumentTypeAlias == "Event" && x.IsVisible()).OrderByDescending(x => x.GetPropertyValue("startDateTime"))
group p by p.GetPropertyValue("startDateTime").Year into yg
select new
{
Year = yg.Key,
Months = from o in yg
group o by o.GetPropertyValue("startDateTime").Month into mg
select new
{
Month = mg.Key,
Items = mg.Select(x => x)
}
};
Using GroupBy to sort a list by year and month
I want so sort a news list by year and month, e.g.
January 2014:
item 1
Item 2
February 2014
item 3
item 4
I'm struggling to do this in Razor using GroupBy:
I can group items by year:
var yearGroups = newsOverview.Descendants("duhubCalendarItem").OrderBy("date desc").GroupBy("date.Year");
But I need to group them by year and month. Is it possible to have nested groups? Or specify year and month in the groupBy clause?
Thanks
Dan
It is possible to use nested groups with LINQ
I have based it on the solution I found: http://stackoverflow.com/questions/6380844/group-posts-by-year-then-by-month?answertab=active#tab-top
I assumed you are using DynamicNode class which will give the following solution:
Which can be accessed like so:
Do not forget to add the using at the top of the razorscript:
This should work :)
This has been super-handy lothar - thanks for posting it :)
I had to modify slightly, but it now works fantastically well:
Thanks for this great post but i have a query!!!! it is set for months but how to set it for the date /day
is working on a reply...