How to use Linq ToDictionary to return a dictionary with multiple values ​​in dictionary elements?

I want to group elements from a linq query under a heading, so for each heading I have a list of objects matching the heading heading. I suggested that a solution would be to use ToDictionary to convert objects, but this only allows one object per "group" (or dictionary). I assumed that I could create a dictionary like (String, List Of ()), but I can’t figure out how to write it.

As an example, I wrote a simplified version below.

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 

The following error

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

What should I do to list for each dictionary?

+6
linq delegates
source share
2 answers

you can first group your entire result by name, and then call dictionnary with the group key as the key

I don't know how to encode it in VB, but how it will look in C #

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

Instead of ToDictionary, you want ToLookup . The search will store a list of values ​​for each key, so the key is no longer required to be unique. However, the search returned by this method is unchanged.

+4
source share

All Articles