Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MVC - Reverse a foreach

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?

like image 440
CLiown Avatar asked Dec 06 '22 11:12

CLiown


2 Answers

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..

like image 88
Michal Klouda Avatar answered Jan 11 '23 20:01

Michal Klouda


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.

like image 23
JasCav Avatar answered Jan 11 '23 20:01

JasCav