Nick LaMarca
Nick LaMarca

Reputation: 8188

Error Returning A Dictionary From A Function

I have created a function to group data..

Private Function GroupData(ByVal validData As DataSet) As Dictionary(Of [String], List(Of DataRow))()

        Dim serviceGroupDataset As DataSet = validData.Clone

        Dim grouped As New Dictionary(Of [String], List(Of DataRow))()
        Dim groupedRows As List(Of DataRow) = New List(Of DataRow)

        For Each r As DataRow In validData.Tables("Detail").[Select]()

            Dim key As [String] = r(AuthorizatonConstants.VA_Authorization_ID).ToString().Split("-"c)(0)

            If Not grouped.TryGetValue(key, groupedRows) Then
                groupedRows = New List(Of DataRow)()
                grouped(key) = groupedRows
            End If

            groupedRows.Add(r)
        Next

//COMPILE ERROR
        Return grouped
    End Function

I am getting a compile error when trying to return the dictionary..

Value of type 'System.Collections.Generic.Dictionary(Of String, System.Collections.Generic.List(Of System.Data.DataRow))' cannot be converted to '1-dimensional array of System.Collections.Generic.Dictionary(Of String, System.Collections.Generic.List(Of System.Data.DataRow))'.

How can I return the grouped dictionary from the function?

Upvotes: 0

Views: 2337

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460168

Your method signature is returning a Dictionary-array(because of the following ()), i assume you want to return a single dictionary.

You can use this Linq-To-DataTable approach which is more comprehensible:

Private Function GroupData(ByVal validData As DataSet) As Dictionary(Of String, List(Of DataRow))   
    Dim groups = From row In validData.Tables("Detail")
                  Let id = row.Field(Of String)(AuthorizatonConstants.VA_Authorization_ID).Split("-"c)(0)
                  Group row By id Into RowGroup = Group
    Dim grouped As Dictionary(Of String, List(Of DataRow)) = groups.
        ToDictionary(Function(grp) grp.id, Function(grp) grp.RowGroup.ToList())    
    Return grouped
End Function

Upvotes: 2

Related Questions