Search code examples
vb.netdictionarylinq-to-sql

public dictionary in todictionary method


I am trying to access the dictionary created in the todictionary method in other procedures.

This is what I'd like but I'm getting a compile error.

Public dctOPT As New Dictionary(Of Integer, Object)

 Sub Get_RTD_OPT()

        Dim lstOPT = From C In DATA.CHAINs, O In DATA.OPTIONs, U In DATA.UDLies
                     Where C.CONTRACT = O.CONTRACT And O.UDLY_SYM = U.UDLY_SYM
                     Select C.ID, C.P_C, C.STRIKE, C.CONTRACT,
                        O.OPT_EXCHANGE, O.OPT_EXPIRY, O.OPT_SEC_TYPE, O.SYM,
                         U.CURRENCY

        dctOPT = lstOPT.ToDictionary(Function(Z) Z.ID)

end sub

This compiles, but then I can't access dctOPT in other procedures.

dim dctOPT = lstOPT.ToDictionary(Function(Z) Z.ID)

Do i need to copy dctOPT into another public dictionary or is there a simpler method? Any suggestions please?


Solution

  • You need this:

    Public dctOPT As New Dictionary(Of Integer, Object)
    
    Sub Get_RTD_OPT()
    
        Dim lstOPT =
            From C In DATA.CHAINs, O In DATA.OPTIONs, U In DATA.UDLies
            Where C.CONTRACT = O.CONTRACT And O.UDLY_SYM = U.UDLY_SYM
            Select C.ID, C.P_C, C.STRIKE, C.CONTRACT,
               O.OPT_EXCHANGE, O.OPT_EXPIRY, O.OPT_SEC_TYPE, O.SYM,
                U.CURRENCY
    
        dctOPT = lstOPT.ToDictionary(Function(Z) Z.ID, Function(Z) CType(Z, Object))
    
    End Sub
    

    Without the Function(Z) CType(Z, Object) the type of the dictionary being created was Dictionary(Of Integer, <anonymous>) and that cannot be directly assigned to Dictionary(Of Integer, Object). The cast correctly generates a dictionary of the right type.