Reputation: 47
Basically my post table:
public partial class Mak
{
public string Name{ get; set; }
public DateTime writingDate{ get; set; }
}
I want to list posts grouped months with for each on my view.
My Code:
@foreach (var tar in Model.Mak.OrderByDescending(x=> x.writingDate.Month).Select(x=> x.writingDate))
{
<a href="/m/[email protected]&[email protected]">@tar.ToString("MMMM yyyy")</a>
@foreach (var mak in Model.Mak.Where(x=> x.writingDate==tar))
{
<a href="/m/@mak.Name"></a><div> @mak.Name</div>
}
}
Output:
July 2017
Connected //post name
July 2017
Linq to SQL
July 2017
OOP
July 2017
Linq Querys
Desired Output:
June 2017
xyz //post name
abc
July 2017
Connected
Linq to SQL
OOP
Linq Querys
How should I write this query?
Upvotes: 1
Views: 185
Reputation: 35232
You can try something like this:
@{
// gets the records grouped based on Year and Month.
// Creates an object of IEnumerable<IGrouping<>> type
var groupedByMonth = Model.Mak
.OrderByDescending(x => x.writingDate)
.GroupBy(x => new { x.writingDate.Year, x.writingDate.Month });
// loop thorugh each group
foreach (var group in groupedByMonth)
{
// each group will have 2 "Keys" with Month and Year value.
// or use Url.Action() to form your anchor
<a href="/m/[email protected]&[email protected]">@group.FirstOrDefault().writingDate.ToString("MMMM yyyy")</a> <br>
// looping through contents of group
// IGrouping inherits from IEnumerable, so this is possible
foreach (var mak in group)
{
<a href="/m/@mak.Name"><div> @mak.Name</div> </a><br>
}
}
}
Upvotes: 1
Reputation: 218762
Group by your collection using month and year and then loop through the grouped items.
@{
var posts = Model.Mak; // Assuming this is the list of posts;
DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
var postGrouped = posts.GroupBy(x => new { Month = x.WritingDate.Month,
Year = x.WritingDate.Year });
}
@foreach (var item in postGrouped)
{
<a href="@Url.Action("date","m",new { year=item.Key.Year, month=item.Key.Month})">
@dtfi.GetAbbreviatedMonthName(item.Key.Month) @item.Key.Year</a>
foreach (var post in item)
{
<div>
<a href="/m/@(post.Title)">@post.Title</a>
</div>
}
}
The GetAbbreviatedMonthName
method takes the integer representing the month and return the string name.
I would also recommend using the html helper methods to render the href value (Use Url.Action
or Html.ActionLink
helper methods) of the link. Also consider following the PascalCasing approach when writing C# classes. (WritingDate
instead of writingDate
)
Upvotes: 0