从函数返回字典时出错

时间:2014-06-02 14:39:49

标签: vb.net

我创建了一个分组数据的功能..

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

尝试返回字典时出现编译错误。

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

如何从函数中返回分组字典?

1 个答案:

答案 0 :(得分:2)

您的方法签名返回Dictionary - 数组(由于以下()),我假设您要返回单个字典。

您可以使用更易于理解的Linq-To-DataTable方法:

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