“LinkedList节点不属于当前LinkedList”

时间:2014-11-26 01:27:55

标签: powershell collections linked-list hashtable

我试图了解如何将哈希表插入到LinkedLists中时遇到了问题。我失去了我尝试过的各种不同的东西。我知道我可以使用ArrayList或其他东西,但我想让它与LinkedLists一起使用,以便我可以对它进行基准测试......

这就是我提出的:

#BEGIN SAMPLE SCRIPT
#------------------------
$list = New-Object Collections.Generic.LinkedList[Hashtable] 

For($i=1; $i -lt 10; $i++){
   $list.AddLast(@{ID=$i; X=100+$i;Y=100+$i}) 
} 

ForEach($item In $list){ 
   If($Item.x -eq 105){ 
       $list.AddAfter($item, @{ID=128;X=128;Y=128}) 
       Break
   } 
}  

ForEach($item In $list){
   write-host "ID:"$item.ID", X:"$item.x", Y:"$item.y", TYPE:" $item.GetType()
}
#-----------------------------------
#END SAMPLE SCRIPT

预期产出:

ID: 1 , X: 101 , Y: 101 , TYPE: System.Collections.Hashtable
ID: 2 , X: 102 , Y: 102 , TYPE: System.Collections.Hashtable
ID: 3 , X: 103 , Y: 103 , TYPE: System.Collections.Hashtable
ID: 4 , X: 104 , Y: 104 , TYPE: System.Collections.Hashtable
ID: 5 , X: 105 , Y: 105 , TYPE: System.Collections.Hashtable
ID: 128 , X: 128 , Y: 128 , TYPE: System.Collections.Hashtable
ID: 6 , X: 106 , Y: 106 , TYPE: System.Collections.Hashtable
ID: 7 , X: 107 , Y: 107 , TYPE: System.Collections.Hashtable
ID: 8 , X: 108 , Y: 108 , TYPE: System.Collections.Hashtable
ID: 9 , X: 109 , Y: 109 , TYPE: System.Collections.Hashtable

我得到的错误:

Exception calling "AddAfter" with "2" argument(s): 
"The LinkedList node does not belong to current LinkedList."

触发错误消息的行:

$list.AddAfter($item, @{ID=128;X=128;Y=128}) 

2 个答案:

答案 0 :(得分:3)

基本上,使用foreach,您会迭代值(hashtable),而不是LinkedListNode,这是AddAfter方法的预期输入。我建议按如下方式迭代列表 -

#BEGIN SAMPLE SCRIPT
#------------------------
$list = New-Object Collections.Generic.LinkedList[Hashtable] 

For($i=1; $i -lt 10; $i++){
   $list.AddLast(@{ID=$i; X=100+$i;Y=100+$i}) 
} 

$current = $list.First

while(-not ($current -eq $null))
{
   If($current.Value.X -eq 105)
   { 
       $list.AddAfter($current, @{ID=128;X=128;Y=128}) 
       Break
   }

   $current = $current.Next
}  

ForEach($item In $list){
   write-host "ID:"$item.ID", X:"$item.x", Y:"$item.y", TYPE:" $item.GetType()
}
#-----------------------------------
#END SAMPLE SCRIPT

答案 1 :(得分:0)

为了让头脑清醒,我看了一眼。问题在于错误的建议。 $item是哈希表,而不是链表列表对象。为了在列表中找到正确的位置,我在Find上执行了$item。一旦完成,我得到了所需的输出。让我觉得有一种更好的方式可以浏览列表......

$list.AddAfter($list.Find($item), @{ID=128;X=128;Y=128}) 

查看对象的数据类型:

$item.GetType().FullName
System.Collections.Hashtable


($list.Find($item)).GetType().Fullname
System.Collections.Generic.LinkedListNode`1[[System.Collections.Hashtable, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

使用ForEach时,似乎不会保留LinkedList中的位置,因此需要使用Find找到位置

对于不熟悉LinkedLists的人,我发现this是一个有用的资源。