I have the following code which outputs a series of links for a nav bar:
<% foreach (var item in (Dictionary<string, string>)ViewData["navItems"])
{
Response.Write(Html.ActionLink(item.Key, item.Value));
}
%>
Is there anyway to alter this code so that the list of links is output in reverse order?
You can use Enumerable.Reverse
method (documentation here):
var dic = (Dictionary<string, string>)ViewData["navItems"];
foreach (var item in dic.Reverse())
{
Response.Write(Html.ActionLink(item.Key, item.Value));
}
Or old school solution: change your foreach cycle to for cycle starting with last item, decrementing index..
Something important that you should note here is that the order of items in a Dictionary is non-deterministic. While you are seeing a particular order right now, it is not guaranteed for Hashtables (of which a Dictionary is). So, even if you use a method to reverse the order, you are not guaranteed of that order in the future and you may experience unplanned results in your solution.
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.
My recommendation is to not enumerate over the Dictionary directly, but, instead, get the values that you want in the form of something that is guaranteed order, such as List<> and sort them at that time and then enumerate through that list in your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With