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

Time:01-29

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 
}

 

CodePudding user response:

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.

  •  Tags:  
  • Related