Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I iterate and remove elements from a list at the same time?

I am iterating through a list of strings and if the string is found in the hashtable then it is deleted from the list. I noticed some odd behavior. If I run the function twice more values are deleted out of on the list on the second run however, my understanding is that I should only need to run it once to delete all values that matched in the hashtable. Do I have my loop setup correctly?

Update: Thanks to the helpful comments I just copied any assets that did not match to the hashtable to a different list and returned it

function Compare()
{
param([System.Collections.Generic.List[string]] $list,
      [Hashtable] $hashtable)
$listTwo = New-Object System.Collections.Generic.List[string]   
for($i=0; $i - lt $list.Count;$i++)
{
 if(($hashtable.$($list[$i])) -ne $null)
 {
 }
 else
 {
  $listTwo.Add($($list[$i])) 
 }
 }
 return $listTwo 
}

 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is usually not a good idea to remove elements from a list that you are iterating. A better idea would be to create another list and append elements to that list if they are not present in the hash table.

function Compare()
{
  param([System.Collections.Generic.List[string]] $list,
        [Hashtable] $hashtable)

  return $list | Where-Object { -not $hashtable.ContainsKey($_) }
}

This method iterates the list and filters the elements by using Where-Object.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading