Home > Enterprise >  Removing a hastable from an arraylist
Removing a hastable from an arraylist

Time:10-28

Well i do get a simple (?) issue : i do not manage to remove a given hashtable from an ArrayList :

$testarraylist = New-Object System.Collections.ArrayList
$testarraylist.Add(1)
$testarraylist.Add(2)
$testarraylist.Add(3)
$testarraylist.Add(4)
$testarraylist.Add(@{1=1})
$testarraylist.Add(@{2=2})
$testarraylist.Add(@{3=3})
$testarraylist.Add(5)
$testarraylist.Add(6)
$testarraylist.Add(7)

i can remove simple "list" element, but i fail at removing the hashtable one

$testarraylist.remove(x)

the only way i found i by using

$testarraylist.removeat(4)

Which work, but aren't there an easier way ? I searched quit a bit and i found lots of exemple but strangely none on this specific case. Well maybe not strange as it may be super easy so that's why no one ever had to ask this question ? or my google skill are failling me ... ?

thanks in advance.

CodePudding user response:

This all comes from how the ArrayList will look for the object you want to remove. If you have a look at the .NET specification again, numbers like System.Int32 are a value types, but collections like System.Collections.Hashtable are reference types.

Basically, what it means, value types are always passed "by value", but for reference types, only a "reference" to that instance is passed.

You can try that out, so 1 -eq 1, because both have the same value, but @{1=1} -ne @{1=1}, because they are two separate instances, and thus two different references.

So, what you would have to do, is store the reference to the original instance in a variable first:

$h = @{1=1}
$testarraylist.Add($h)
$testarraylist.Remove($h)

Because this is such a basic and important concept in .NET, and basically all programming languages, I recommend you to take a few minutes and read more about it.

  • Related