哈希表和键顺序 [英] Hashtables and key order

查看:99
本文介绍了哈希表和键顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在添加键时将键的顺序保持在哈希表中?就像推送/弹出机制一样.

Is there a way to keep the order of keys in a hashtable as they were added? Like a push/pop mechanism.

示例:

$hashtable = @{}

$hashtable.Add("Switzerland", "Bern")
$hashtable.Add("Spain", "Madrid")
$hashtable.Add("Italy", "Rome")
$hashtable.Add("Germany", "Berlin")
$hashtable

我想保留将元素添加到哈希表的顺序.

I want to retain the order in which I've added the elements to the hashtable.

推荐答案

PowerShell V1/V2中没有内置解决方案.您将要使用.NET System.Collections.Specialized.OrderedDictionary :

There is no built-in solution in PowerShell V1 / V2. You will want to use the .NET System.Collections.Specialized.OrderedDictionary:

$order = New-Object System.Collections.Specialized.OrderedDictionary
$order.Add("Switzerland", "Bern")
$order.Add("Spain", "Madrid")
$order.Add("Italy", "Rome")
$order.Add("Germany", "Berlin")


PS> $order

Name                           Value
----                           -----
Switzerland                    Bern
Spain                          Madrid
Italy                          Rome
Germany                        Berlin

在PowerShell V3中,您可以强制转换为[有序]:

In PowerShell V3 you can cast to [ordered]:

PS> [ordered]@{"Switzerland"="Bern"; "Spain"="Madrid"; "Italy"="Rome"; "Germany"="Berlin"}

Name                           Value
----                           -----
Switzerland                    Bern
Spain                          Madrid
Italy                          Rome
Germany                        Berlin

这篇关于哈希表和键顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆