Hashtable vs array of user objects in relation to iteration

I often write lists of things and do enumerations against them to do some get / set.

I hate listing hash tables, because whenever I need it, I have to lean back to work with hashtable objects.

 $hashtablelistofitems = @{} $hashtablelistofitems.add("i'm a key", "i'm a value") foreach ($item in $hashtablelistofitems.keys) { $item $hashtablelistofitems.item($item) } 

Instead, I usually revert to using a one-dimensional array of a custom object with two non-elements.

 $array = @() $listofitems = "" | select key,value $listofitems.key = "i'm a key" $listofitems.value = "i'm a value" $array += $listofitems foreach ($item in $listofitems) { $item.key $item.value } 

Why should I use hashtable on this method? Just because it guarantees only one value per key?

+5
source share
2 answers

You should use a hash table if you want to save a list of key values, and not create an array containing a custom object with two properties (key / values), mainly for two reasons:

  • You might want to pass your hash table to a function that expects a hash table.
  • Hashtable is the built-in PowerShell type that users are aware of. Your second approach is harder to read / maintain for other users.

Note: You can iterate over a hash table in much the same way as your approach by calling the GetEnumerator() function:

 foreach ($item in $listofitems.GetEnumerator()) { $item.key $item.value } 

In addition, the hash table comes with convenient methods that you can use:

 @{} | Get-Member | Where-Object MemberType -eq Method | Select Name 

Output:

 Name ---- Add Clear Clone Contains ContainsKey ContainsValue CopyTo Equals GetEnumerator GetHashCode GetObjectData GetType OnDeserialization Remove ToString 
+5
source

This is not as useful as Martin's compilation, but it is quite useful.

This is an MSDN article on how to convert back and forth between Hashtables and PSCustomObjects. Article

+2
source

Source: https://habr.com/ru/post/1268032/


All Articles