Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# .NET 2.0, what's an easy way to do a foreach in reverse?

Lets say I have a Dictionary object:

Dictionary myDictionary<int, SomeObject> = new Dictionary<string, SomeObject>();

Now I want to iterate through the dictionary in reverse order. I can't use a simple for loop because I don't know the keys of the dictionary. A foreach is easy:

foreach (SomeObject object in myDictionary.Values)
{
    // Do stuff to object
}

But how can I perform this in reverse?

like image 871
Pandincus Avatar asked Sep 17 '08 13:09

Pandincus


3 Answers

A dictionary or any other form of hashtable has no ordering. So what you are trying to do is pointless :)

like image 75
leppie Avatar answered Oct 13 '22 00:10

leppie


I'd use a SortedList instead of a dictionary. You can still access it by Key, but you can access it by index as well.

SortedList sCol = new SortedList();

sCol.Add("bee", "Some extended string matching bee");
sCol.Add("ay", "value matching ay");
sCol.Add("cee", "Just a standard cee");

// Go through it backwards.
for (int i = sCol.Count - 1; i >=0 ; i--)
    Console.WriteLine("sCol[" + i.ToString() + "] = " + sCol.GetByIndex(i));

// Reference By Key
foreach (string i in sCol.Keys)
    Console.WriteLine("sCol[" + i + "] = " + sCol[i]);

// Enumerate all values
foreach (string i in sCol.Values)
    Console.WriteLine(i);

It's worth noting that a sorted list stores key/value pairs sorted by key only.

like image 34
Jonathan Avatar answered Oct 12 '22 22:10

Jonathan


If you have .NET 3.5 you can use the .Reverse() extension method on IEnumerables. For example:

foreach (object o in myDictionary.Values.Reverse())
{
     // Do stuff to object
}
like image 33
Chris Wenham Avatar answered Oct 12 '22 22:10

Chris Wenham