1

我不确定确切的术语,但我尝试使用 LINQ 做的是用它的孩子的键“切换”字典的键。

这是我作为输入得到的集合:

Key:HeaderID Value:
 Key:ItemID Value:Object
 Key:ItemID Value:Object
 Key:ItemID Value:Object
Key:HeaderID Value:
 Key:ItemID Value:Object
 Key:ItemID Value:Object
 Key:ItemID Value:Object
Key:HeaderID Value:
 Key:ItemID Value:Object
 Key:ItemID Value:Object
 Key:ItemID Value:Object

这是我想要作为输出的集合:

Key:ItemID Value:
 Key:HeaderID Value:Object
 Key:HeaderID Value:Object
 Key:HeaderID Value:Object
Key:ItemID
 Key:HeaderID Value:Object
 Key:HeaderID Value:Object
 Key:HeaderID Value:Object  
Key:ItemID
 Key:HeaderID Value:Object
 Key:HeaderID Value:Object
 Key:HeaderID Value:Object

我已经在 VB.net 中创建了代码:

    Dim objInput As Dictionary(Of String, Dictionary(Of String, Object)) = fakefunction()
  ' ItemID -> HeaderID ColumnValue
    Dim objOutput As New Dictionary(Of String, Dictionary(Of String, Object))

    For Each strHeaderID As String In objInput.Keys

        Dim objColumnValuesPerItem As Dictionary(Of String, Object) = objInput(strHeaderID)

        For Each strItemID As String In objColumnValuesPerItem.Keys

            Dim objColumnValue As Object = objColumnValuesPerItem(strItemID)

            If Not objOutput.ContainsKey(strItemID) Then
                objOutput.Add(strItemID, New Dictionary(Of String, Object))
            End If

            objOutput(strItemID).Add(strHeaderID, objColumnValue)

        Next

    Next

我问这个问题的原因是纯粹的教育,我曾尝试使用 LINQ 将其转换为正确的列表,但如果不创建非常复杂且冗长的 LINQ 语句,我将一事无成。

4

1 回答 1

2

我不知道任何 VB.Net,但我认为这应该做你想要的。

Dim objOutput As Dictionary(Of String, Dictionary(Of String, Object)) =
    objInput _
        .SelectMany(Function(oKvp) oKvp.Value.Select(Function(iKvp) New With { _
            .OuterKey = oKvp.Key, _
            .InnerKey = iKvp.Key, _
            .Value = iKvp.Value})) _
        .GroupBy(Function(tri) tri.InnerKey) _
        .ToDictionary( _
            Function(g) g.Key, _
            Function(g) g.ToDictionary( _
                Function(tri) tri.OuterKey, _
                Function(tri) tri.Value))

基本上,您将整个嵌套字典扁平化为具有键和值的对象序列,然后按内部键对它们进行分组,然后再转换回嵌套字典。

于 2012-07-18T14:54:39.757 回答