Reputation: 61
I'm having problems doing a For Each loop on a "List(Of KeyValuePair(Of" collection.
I'm passing a ParamArray to a Function
ParamArray args() As List(Of KeyValuePair(Of String, Integer))
I'm then trying to do a For Each on the Collection
For Each arg As KeyValuePair(Of String, Integer) In args
The error I'm getting is:
Value of type 'System.Collections.Generic.List(Of System.Collections.Generic.KeyValuePair(Of String, Integer))' cannot be converted to 'System.Collections.Generic.KeyValuePair(Of String, Integer)'
I just can't figure out how to do this, and I can't find any examples of how to do this.
My only thought right now is to do
For Each arg As Object In args
Then converting the object to a KeyValuePair, but there must be a neater way of doing this...
Upvotes: 2
Views: 5809
Reputation: 26454
This declares an array of lists:
ParamArray args() As List(Of KeyValuePair(Of String, Integer))
You probably meant an array of KVP (option #1):
ParamArray args As KeyValuePair(Of String, Integer)
Or (option #2):
args() As KeyValuePair(Of String, Integer)
Or (option #3):
args As List(Of KeyValuePair(Of String, Integer))
Upvotes: 1
Reputation: 4593
args
is an array. That means that you have an array of List(Of KeyValuePair(Of String, Integer))
.
To access each item in a for each you will need to do this (untested):
For Each arg As List(Of KeyValuePair(Of String, Integer)) In args
For Each kvp as KeyValuePair(Of String, Integer) In arg
' Do Stuff
Next
Next
As per my comment above: you'd probably be better off using a Dictionary(Of String, Integer)
and some Linq statements.
Edit: Also, depending on what you're trying to do with each item, modifying the item in any way will result in an exception because you can't modify a collection you're iterating over.
Upvotes: 5