I have a dictionary
Dictionary<string, string> myDict = new Dictionary<string, string>()
{
{ "country", "1" },
{ "state", "2" },
{ "name", "3" },
{ "type", "4" }
};
I want to arrage the dictionary elements in a specific order shown below
Dictionary<string, string> myDict = new Dictionary<string, string>()
{
{ "name", "3" },
{ "type", "4" },
{ "country", "1" },
{ "state", "2" }
};
Is it possible for dictionary type? I would appreciate it if you give a solution for that
No, you can't rely on the order in a Dictionary
. It's implementation-specific, and can change in unexpected ways.
In this case, it sounds like really you should have a custom type instead, with Country
, State
, Name
and Type
properties.
An alternative would be to have a separate list of well-known keys in the order you want - you can always iterate over that and fetch the appropriate key:
foreach (var key in keysInOrder)
{
Console.WriteLine("{0}: {1}", key, dictionary[key]);
}
If you really really want an IDictionary<,>
in a particular order, you could always implement it yourself, maintaining a key order as a list and a Dictionary<,>
internally. But this feels like a design smell, to be honest.
See more on this question at Stackoverflow