Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Actually, in C# 2.0 you can create your own iterator that traverses a container in reverse. Then, you can use that iterator in your foreach statement. But your iterator would have to have a way of navigating the container in the first place. If it's a simple array, it could go backwards like this:</p> <pre><code>static IEnumerable&lt;T&gt; CreateReverseIterator&lt;T&gt;(IList&lt;T&gt; list) { int count = list.Count; for (int i = count - 1; i &gt;= 0; --i) { yield return list[i]; } } </code></pre> <p>But of course you can't do that with a Dictionary as it doesn't implement IList or provides an indexer. Saying that a Dictionary does not have order is not true: of course it has order. That order can even be useful if you know what it is.</p> <p>For a solution to your problem: I'd say copy the elements to an array, and use the above method to traverse it in reverse. Like this:</p> <pre><code>static void Main(string[] args) { Dictionary&lt;int, string&gt; dict = new Dictionary&lt;int, string&gt;(); dict[1] = "value1"; dict[2] = "value2"; dict[3] = "value3"; foreach (KeyValuePair&lt;int, string&gt; item in dict) { Console.WriteLine("Key : {0}, Value: {1}", new object[] { item.Key, item.Value }); } string[] values = new string[dict.Values.Count]; dict.Values.CopyTo(values, 0); foreach (string value in CreateReverseIterator(values)) { Console.WriteLine("Value: {0}", value); } } </code></pre> <p>Copying your values to an array may seem like a bad idea, but depending on the type of value it's not really that bad. You might just be copying references!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload