【问题标题】:How do I use Linq ToDictionary to return a dictionary with multiple values in the dictionary items?如何使用 Linq ToDictionary 在字典项中返回具有多个值的字典?
【发布时间】:2010-01-25 19:15:59
【问题描述】:

我想将 linq 查询中的项目分组到标题下,这样对于每个标题,我都有一个与标题标题匹配的对象列表。我假设解决方案是使用 ToDictionary 来转换对象,但这只允许每个“组”(或字典键)一个对象。我以为我可以创建类型为 (String, List Of()) 的字典,但我不知道如何编写它。

作为一个例子,我在下面写了一个简化版本。

Public Class order
    Public ID As Integer
    Public Name As String
    Public DateStamp As Date
End Class
Public Function GetOrdersSortedByDate() As Generic.Dictionary(Of String, Generic.List(Of User))
    Dim orders As New List(Of order)(New order() _
    {New order With _
     {.ID = 1, .Name = "Marble", .DateStamp = New Date(2010, 1, 1)}, _
     New order With _
     {.ID = 2, .Name = "Marble", .DateStamp = New Date(2010, 5, 1)}, _
     New order With _
     {.ID = 3, .Name = "Glass", .DateStamp = New Date(2010, 1, 1)}, _
     New order With _
     {.ID = 4, .Name = "Granite", .DateStamp = New Date(2010, 1, 1)}})

    ' Create a Dictionary that contains Package values, 
    ' using TrackingNumber as the key.
    Dim dict As Dictionary(Of String, List(Of order)) = _
        orders.ToDictionary(Of String, List(Of order))(Function(mykey) mykey.Name, AddressOf ConvertOrderToArray) ' Error on this line

    Return dict
End Function
Public Function ConvertOrderToArray(ByVal myVal As order, ByVal myList As Generic.List(Of order)) As Generic.List(Of order)
    If myList Is Nothing Then myList = New Generic.List(Of order)
    myList.Add(myVal)
    Return myList
End Function

报错如下

'Public Function ConvertOrderToArray(myVal As order, myList As System.Collections.Generic.List(Of order)) As System.Collections.Generic.List(Of order)'
does not have a signature compatible with delegate 
'Delegate Function Func(Of order, System.Collections.Generic.List(Of order))(arg As order) As System.Collections.Generic.List(Of order)'.

如何为每个字典项输出一个列表?

【问题讨论】:

    标签: vb.net linq delegates


    【解决方案1】:

    您可以先按名称对所有结果进行分组,然后以组键为键调用字典

    我不知道如何在 VB 中编写代码,但在 C# 中会是什么样子

     Dictionary<string,List<Order>> dict = orders
      .GroupBy(x => x.Name)
      .ToDictionary(gr => gr.Key,gr=>gr.ToList() );
    

    【讨论】:

    • Dim f = d.GroupBy(Function(x) x.PoolName).ToDictionary(Function(t) t.Key, Function(g) g.ToList()) - 我给它去吧!
    【解决方案2】:

    您需要ToLookup 而不是ToDictionary。查找将存储每个键的值列表,因此不再要求键是唯一的。但是,从此方法返回的查找是不可变的。

    【讨论】:

    • 这个想法是为每个键设置多个项目,因此目的是使其具有唯一性。查找可枚举吗?
    • 是的,它作为文档中提到的组的枚举:msdn.microsoft.com/en-us/library/bb460184.aspx 它完全符合公认的解决方案的功能,但它是一个内置函数:orders.ToLookup(x => x.Name, x => x);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多