我有一本字典
Dictionary<string, string> myDict = new Dictionary<string, string>()
{
{ "country", "1" },
{ "state", "2" },
{ "name", "3" },
{ "type", "4" }
};
我想按照下面显示的特定顺序列出字典元素
Dictionary<string, string> myDict = new Dictionary<string, string>()
{
{ "name", "3" },
{ "type", "4" },
{ "country", "1" },
{ "state", "2" }
};
词典类型有可能吗?如果你给出一个解决方案,我将不胜感激
答案 0 :(得分:4)
不,您不能依赖Dictionary
中的订单。它是特定于实现的,并且可能以意想不到的方式发生变化。
在这种情况下,听起来像真的你应该有一个自定义类型,Country
,State
,Name
和Type
属性。
另一种方法是按照您想要的顺序拥有一个众所周知的密钥列表 - 您可以随时遍历 并获取相应的密钥:
foreach (var key in keysInOrder)
{
Console.WriteLine("{0}: {1}", key, dictionary[key]);
}
如果你真的确实希望按特定顺序IDictionary<,>
,你可以自己实现它,将一个关键顺序维护为列表和 a {内部{1}}但说实话,这就像是一种设计气味。