locked
Sorting a hashtable within a hashtable RRS feed

  • Question

  • So to create a hastable within a hashtable, as way of a multi dimensional table we do something like this :-

    $testtable = @{}

    $testtable.Add("TestKey1", (@{"items" = "0"; "size" = "4"}))

    Output is :-

    Name                           Value
    ----                           -----
    TestKey1                       {items, size}

    And you can reference anything like $testtable.TestKey1.size will give the output of 4 as expected.

    This is all good and well, this works for the most part....but I want to be able to sort the tables on the multiple items.  For instance I want to sort the table first on the value of items, and then on the value of size.  So if we had a table like this :-

    TestKey1.Items = 10
    TestKey1.Size = 1
    TestKey2.Items = 9
    TestKey2.Size = 3
    TestKey3.Items = 9
    TestKey3.Size = 2

    If we sort the table by Items then Size it should be in the following order

    TestKey3, 9, 2
    TestKey2, 9, 3
    TestKey1, 10, 1

    But I cannot work out for the life of me what to pass back to the sort-object command to sort hash tables when they are constructed like this.  I guess I can do the same thing with just creating a hashtable of objects but I would like to do it like this.

    Thursday, April 4, 2013 12:37 PM

Answers

  • It's going to be a statstic board that gets updated and then resorted so we take the one with the least items, then least space.

    I sat back and had a think on it, I worked it out myself actually...if we do this :-

    $testtable.getenumerator() | Sort-Object -Property @{Expression={$_.Value["size"]}}) it works as one would expect.

    • Marked as answer by Bill_Stewart Thursday, April 4, 2013 2:22 PM
    Thursday, April 4, 2013 2:10 PM

All replies

  • What's the purpose of this exercise, when you can create arrays of PSObjects containing whatever properties you want?

    Bill

    Thursday, April 4, 2013 1:59 PM
  • It's going to be a statstic board that gets updated and then resorted so we take the one with the least items, then least space.

    I sat back and had a think on it, I worked it out myself actually...if we do this :-

    $testtable.getenumerator() | Sort-Object -Property @{Expression={$_.Value["size"]}}) it works as one would expect.

    • Marked as answer by Bill_Stewart Thursday, April 4, 2013 2:22 PM
    Thursday, April 4, 2013 2:10 PM