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/Date?year=@tar.Year&month=@tar.Month">@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?
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/Date?year=@group.Key.Year&month=@group.Key.Month">@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>
}
}
}