Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate a dictionary<string,string> in reverse order(from last to first) in C#?

Tags:

c#

c#-4.0

I have one Dictionary and added some elements on it.for example,

Dictionary<string, string> d = new Dictionary<string, string>();

d.Add("Content","Level0");
d.Add("gdlh","Level1");
d.Add("shows","Level2");
d.Add("ytye","Level0");

In C#, Dictionary keeps elements in natural order.But i now want to iterate those values from last to first(ie, Reverse order).i mean,

first i want to read ytye then shows,gdlh and finally Content.

Please guide me to get out of this issue...

like image 450
Saravanan Avatar asked Apr 16 '12 11:04

Saravanan


People also ask

How do I reverse the order of a dictionary in dictionary?

Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.

How do I reverse the order of a dictionary in python?

Method #1 : Using OrderedDict() + reversed() + items() This method is for older versions of Python. Older versions don't keep order in dictionaries, hence have to converted to OrderedDict to execute this task.

How do you iterate through a list backwards in Python?

Use the reversed() function to iterate over a list in reverse order, e.g. for item in reversed(my_list): . The reversed() function takes an iterator, such as a list, reverses it and returns the result.


1 Answers

Maybe OrderByDescending on the key. Like this:

d.OrderByDescending (x =>x.Key)

Foreach like this:

foreach (var element in d.OrderByDescending (x =>x.Key))
{

}
like image 173
Arion Avatar answered Nov 16 '22 12:11

Arion