如何将Hashtable中的两个项添加到另一Hashtable?代码实现疑问
htOutputDetails Ah, I see the issue here—your approach of using lsListHashtables.Item(0, 1) won’t work because the Item property of a List(Of Hashtable) only accepts a single integer index to fetch one element at a time. There’s no built-in way to "combine" two Hashtables from the list using a multi-index syntax like that. Instead, you’ll need to retrieve each Hashtable separately and manually copy the entries you want into htOutputDetails.
Let’s cover two common scenarios:
1. Add all entries from the second Hashtable (index 1)
If you want to copy every key-value pair from the Hashtable at index 1 into htOutputDetails, use a loop to iterate through the source Hashtable’s entries:
' Grab your target Hashtable (the one at index 0) Dim htOutputDetails As Hashtable = CType(lsListHashtables.Item(0), Hashtable) ' Grab the source Hashtable (the one at index 1 you want to pull entries from) Dim htSource As Hashtable = CType(lsListHashtables.Item(1), Hashtable) ' Loop through each key in the source and add to the target For Each key As Object In htSource.Keys ' This will overwrite existing keys in htOutputDetails if they match htOutputDetails(key) = htSource(key) Next
If you want to avoid overwriting existing keys in htOutputDetails, add a quick check before adding:
For Each key As Object In htSource.Keys If Not htOutputDetails.ContainsKey(key) Then htOutputDetails.Add(key, htSource(key)) End If Next
2. Add only specific entries from the second Hashtable
If you only need two particular items (say, keys named "UserId" and "UserName"), you can add them individually with safety checks:
Dim htOutputDetails As Hashtable = CType(lsListHashtables.Item(0), Hashtable) Dim htSource As Hashtable = CType(lsListHashtables.Item(1), Hashtable) ' Add specific keys only if they exist in the source Hashtable If htSource.ContainsKey("UserId") Then htOutputDetails("UserId") = htSource("UserId") End If If htSource.ContainsKey("UserName") Then htOutputDetails("UserName") = htSource("UserName") End If
Why your original code failed
The Item property (or its shortcut lsListHashtables(0)) is meant to retrieve a single element from the list. Passing two indices (0,1) isn’t valid syntax here—there’s no overload that combines elements for you. You have to handle the merging manually by copying entries between the Hashtables.
内容的提问来源于stack exchange,提问作者LukasDreams

