CLiown
CLiown

Reputation: 13843

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?

Upvotes: 4

Views: 2946

Answers (3)

I am not sure if you want it sorted. If you do you can use the following. If you just want it reversed Reverse() is what you want.

This gives you the list in revers order on key. You can change c.Key to c.Value if you want to travers the list in order of value instead.

var dict = new Dictionary<string, string>() {{"a", "1"}, {"b", "2"}, {"c", "3"}};

foreach (var keyValuePair in dict.OrderByDescending(c => c.Key))
{
    Console.WriteLine(keyValuePair.Value);
}

Upvotes: 2

JasCav
JasCav

Reputation: 34652

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.

Upvotes: 5

Michal Klouda
Michal Klouda

Reputation: 14521

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

Upvotes: 8

Related Questions