Reputation: 11592
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
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
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