Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most-succinct way to search an array of hash tables for a key

Assuming:

$columnArray = @(
  @{Name='COL_A';Type=[int];Measurements=@()},
  @{Name='COL_B';Type=[string];Measurements=@()},
  @{Name='COL_C';Type=[datetime];Measurements=@()}
)

Using the Where-Object command to get COL_B's Measurements array:

($Fields | ? { $_.Name -eq 'COL_B' }).Measurements

Is there a more-succinct way of doing this? Would a nested set of PSCustomObjects be a better approach?

like image 876
craig Avatar asked Jan 08 '23 08:01

craig


2 Answers

You could modify the array itself with a method to do the finding:

Add-Member -InputObject $columnArray -MemberType ScriptMethod -Name FindCol -Value { param([String]$Column) $this | ? { $_.Name -eq $Column }  }

Then you can do:

$columnArray.FindCol('COL_B').Measurements

Or you can do:

Add-Member -InputObject $columnArray -MemberType ScriptMethod -Name GetMeasurements -Value { param([String]$Column) $this | ? { $_.Name -eq $Column } | Select-Object -ExpandProperty Measurements  }

Then:

$columnArray.GetMeasurements('COL_B')
like image 109
briantist Avatar answered Apr 26 '23 21:04

briantist


If you are interested in looking element by key, than Hashtable will be better approach than array.

$columnHashtable=@{
    COL_A=@{Type=[int];Measurements=@()}
    COL_B=@{Type=[string];Measurements=@()}
    COL_C=@{Type=[datetime];Measurements=@()}
}

With Hashtable you can get Measurements array of COL_B by this command:

$columnHashtable.COL_B.Measurements

And If you want to enumerate all elements in Hashtable, then you can use following command:

$columnHashtable.GetEnumerator()|ForEach-Object ...

In case if order of elements in hash table matters, you could use [ordered] operator before hash table literal to create OrderedDictionary instead of Hashtable.

like image 21
user4003407 Avatar answered Apr 26 '23 22:04

user4003407