2

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...

Brandon
  • 4,491
  • 6
  • 38
  • 59
JA12
  • 61
  • 1
  • 4
  • 12

2 Answers2

5

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.

Brandon
  • 4,491
  • 6
  • 38
  • 59
  • 1
    Thanks for that, this option worked fine. This ParamArray is for a flexible number of Parameters. The original code (VB6) used Optional and isMissing, which I can't do in VB.NET, this was my solution. – JA12 Sep 04 '14 at 15:47
  • 1
    Glad my solution worked. Would you mind marking the question as answered for future reference? – Brandon Sep 04 '14 at 15:48
  • 1
    Click the checkmark beside my answer. It will turn green which will mark the question as answered. – Brandon Sep 04 '14 at 15:54
  • 1
    OK, that wasn't obvious. I was looking at the top for something relating to the original question... – JA12 Sep 05 '14 at 08:15
1

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))
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151