Using callbyname to check list.contains(x)

241 views Asked by At

I've been trying to use callbyname to write a generic function which checks if the target list (targetListName) contains a certain item before adding it to the list. Unfortunately, I can't seem to figure out how to use .contains with callbyname. Appreciate any help!

This is the code I'm using now. Supply and Demand are both lists(of string).

Public Sub addItem(ByVal item As String, ByVal targetListName As String)
    Select Case targetListName.ToLower
        Case "supply"
            If supply.Contains(item) = False Then supply.Add(targetListName)
        Case "demand"
            If demand.Contains(item) = False Then supply.Add(targetListName)
        Case Else
            'bugcatch
    End Select
End Sub

I would like to ideally use something like this instead:

Public Sub addItem(ByVal item As String, ByVal targetListName As String)
    If CallByName(Me, targetListName, [Method]).Contains(item) = false Then
        CallByName(Me, targetListName, [Set]).Add(item)
    End If
End Sub
2

There are 2 answers

2
jcwrequests On BEST ANSWER

You could just have a dictionary of lists with string as your key. Not sure what the real benefit of is of using CallByName. Could you elaborate on that more on the use case and problem you are trying to solve?

0
Neaox On

Unfortunately the CallByName function does not work like that. See http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.interaction.callbyname.aspx

A workaround might be to do it this way:

Public Function getListByName(ByVal targetListName As String) As List(of Object)
    Select Case targetListName.ToLower
        Case "supply"
            return supply
        Case "demand"
            return demand
        Case Else
            'bugcatch
    End Select
    return Nothing
End Function

Public Sub addItem(ByVal item As String, ByVal targetListName As String)
    dim list As List(of Object) = GetListByName(targetListName)
    If not list.Contains(item) Then
        list.Add(item)
    End If
End Sub

Alternatively you could use reflection to get your list:

Public Function getListByName(ByVal targetListName As String) As Object
    dim field = Me.GetType().GetField(targetListName)
    If field IsNot Nothing then
        return field.GetValue(Me)
    End If
    return Nothing
End Function

If possible I would go with @user2759880 suggestion if the number of lists does not change very often.