ค้นหาเว็บไซต์

การเรียงลำดับตารางแฮช


สมมติว่าคุณมีตารางแฮชง่ายๆ เช่นนี้:

$hash = @{
Name="Jeff"
Size = 123
Color = "Green"
Computer = "Yoga2Pro"
}

และแสดงได้ดังนี้:

PS C:\scripts> $hash

Name                           Value
----                           -----
Color                          Green
Name                           Jeff
Computer                       Yoga2Pro
Size                           123

ในการเรียงลำดับคีย์ คุณสามารถใช้เมธอด GetEnumerator() ซึ่งเป็นส่วนหนึ่งของออบเจ็กต์ตารางแฮชทุกรายการ วิธีการนี้สร้างวัตถุSystem.Collections.DictionaryEntryสำหรับแต่ละรายการในตารางแฮช

PS C:\scripts> $hash.GetEnumerator()  | get-member


   TypeName: System.Collections.DictionaryEntry

Name        MemberType    Definition
----        ----------    ----------
Name        AliasProperty Name = Key
Equals      Method        bool Equals(System.Object obj)
GetHashCode Method        int GetHashCode()
GetType     Method        type GetType()
ToString    Method        string ToString()
Key         Property      System.Object Key {get;set;}
Value       Property      System.Object Value {get;set;}

ซึ่งหมายความว่าคุณสามารถจัดเรียงทรัพย์สินใดก็ได้

PS C:\scripts> $hash.GetEnumerator() | sort key

Name                           Value
----                           -----
Color                          Green
Computer                       Yoga2Pro
Name                           Jeff
Size                           123


PS C:\scripts> $hash.GetEnumerator() | sort value

Name                           Value
----                           -----
Size                           123
Color                          Green
Name                           Jeff
Computer                       Yoga2Pro

อย่างไรก็ตาม เริ่มต้นใน PowerShell 3.0 คุณสามารถ "จัดเรียงล่วงหน้า" ตารางแฮชโดยกำหนดเป็น "เรียงลำดับ"

$hash = [ordered]@{
Name="Jeff"
Computer = "Yoga2Pro"
Color = "Green"
Size = 123
}

ตอนนี้ตารางแฮชจะถูกจัดเรียงตามลำดับที่คุณกำหนดไว้เสมอ

PS C:\scripts> $hash

Name                           Value
----                           -----
Name                           Jeff
Computer                       Yoga2Pro
Color                          Green
Size                           123

แม้ว่าถ้าคุณต้องการเรียงลำดับคุณก็ยังทำได้

PS C:\scripts> $hash.GetEnumerator() | sort name -Descending

Name                           Value
----                           -----
Size                           123
Name                           Jeff
Computer                       Yoga2Pro
Color                          Green

ขอให้มีสัปดาห์ที่ดีและฉันหวังว่าคุณจะจัดการเรื่องต่างๆ ได้

บทความที่เกี่ยวข้อง