Saravanan
Saravanan

Reputation: 11592

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

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

Upvotes: 14

Views: 17095

Answers (4)

Arion
Arion

Reputation: 31239

Maybe OrderByDescending on the key. Like this:

d.OrderByDescending (x =>x.Key)

Foreach like this:

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

}

Upvotes: 7

Louis Kottmann
Louis Kottmann

Reputation: 16628

It's available with Linq: d.Reverse()

Upvotes: 2

yamen
yamen

Reputation: 15618

Use LINQ Reverse, but note that does not reverse in place:

var reversed = d.Reverse();

But note that this is not a SortedDictionary, so the order is not necessarily guaranteed in the first place. Perhaps you want OrderByDescending instead?

Upvotes: 10

Phil
Phil

Reputation: 42991

Just use the Linq extension method Reverse

e.g.

foreach( var item in d.Reverse())
{
    ...
}

Upvotes: 23

Related Questions