Reputation: 119
I have a BudgetHistory
class and in that class I have Title
property declared as public string Title
. The title is set to the month and year of the BudgetHistory
item so if you want to look at the history of the February budget for the year 2017 then the name of that is February 2017. I am trying to order the string so that the months appear in chronological order when they are iterated over. So when I do my foreach
loop over my BudgetHistory
model the list should appear as Jan., Feb., March, etc. How would I go about doing this?
This is what my foreach
loop looks like right now:
<ul class="treeview-menu">
@foreach (var item in (from w in Model group w by w.Title into n select n))
{
<li><a href="@Url.Action("Index", "BudgetHistories", new { Title = item.First().Title })"><i class="fa fa-dollar"></i> <span>@item.First().Title</span></a></li>
}
</ul>
The reason I have it set up the way it is above is because there are many transactions with the same title and I am grouping those transactions by the title and just displaying all those transactions with that title.
Upvotes: 1
Views: 719
Reputation: 4693
GroupBy and Reverse does not sort your data it might be working because Title
is sorted in your data but you can change its order and then try to Group
and Reverse
to check its still sorted
you can try this
<ul class="treeview-menu">
@foreach (var item in (Model.OrderBy(x => DateTime.ParseExact(x.Title, "MMMM yyyy", CultureInfo.InvariantCulture) ).GroupBy(x=>x.Title)))
{
<li><a href="@Url.Action("Index", "BudgetHistories", new { Title = item.First().Title })"><i class="fa fa-dollar"></i> <span>@item.First().Title</span></a></li>
}
</ul>
in above code DateTime.ParseExact
converts the February 2017
to DateTime
format,
Here MMMM yyyy
represents DateTime Format of your Title
because you can sort datetime and OrderBy is used to sort the data in assending order
Upvotes: 1
Reputation: 35477
You could add a propery that converts the Title
to a DateTime
and then sort by this value.
This method will be useful in the future, such as getting a budget for a quarter or a year.
public DateTime When
{
get
{
// The next 2 variables should really be static to the class.
var culture = CultureInfo.CreateSpecificCulture("en-US");
var format = "MMMM yyyy";
return DateTime.ParseExact(this.Title, format, culture);
}
}
@foreach (var item in (Model.OrderBy(x => x.When)))
{
<li><a href="@Url.Action("Index", "BudgetHistories",
new { Title = item.Title })">
<i class="fa fa-dollar"></i>
<span>@item.Title</span></a>
</li>
}
Upvotes: 0