2010-01-25 31 views
6

我想從一個標題下的linq查詢分組項目,以便每個標題我有一個匹配標題標題的對象列表。我認爲解決方案是使用ToDictionary來轉換對象,但這隻允許每個「組」(或字典鍵)一個對象。我認爲我可以創建類型(String,List Of())的字典,但我無法弄清楚如何編寫它。如何使用Linq ToDictionary返回字典項目中包含多個值的字典?

作爲一個例子,我在下面寫了一個簡化版本。

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

我該怎麼做,以輸出每個字典項目的列表?

回答

13

你可以先將所有的結果的名字,然後叫同組鍵鍵

到dictionnary我不知道如何把它在VB代碼,但它看起來像在C#什麼

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

昏暗F = d.GroupBy(功能(X)x.PoolName).ToDictionary(功能(T)t.Key,函數(G)g.ToList()) - 我給它一個去! – digiguru 2010-01-26 21:28:08

+0

這就像一個夢想,謝謝 – digiguru 2010-01-26 23:12:43

4

代替ToDictionary,您需要ToLookup。查找將存儲每個鍵的值列表,因此該鍵不再是唯一的。然而,從這個方法返回的查找是不可變的。

+0

這個想法是爲每個鍵有多個項目,所以其目的是讓它具有唯一性。查找可枚舉嗎? – digiguru 2010-01-26 23:10:34

+0

是的,它枚舉在文件中所提及groupsas:http://msdn.microsoft.com/en-us/library/bb460184.aspx 它確實接受的解決方案做什麼,但一個內置的功能: orders.ToLookup(x => x.Name,x => x); – 2010-01-26 23:51:36

相關問題