[英]Dictionary in VB.NET obtain keys grouped
嗨我有這本字典..
Dim Rooms As New Dictionary(Of Integer, Of Integer)
Rooms(1) = 101, 102, 109, 110
Rooms(2) = 103, 104, 105
Rooms(3) = 106, 107
我想知道我是否可以獲得字典中有多少鍵
例如,在這本詞典中我有3個鍵,如果我使用Rooms.Count,它返回我的每一對鍵值,但我想獲得3,每個不同的值作為鍵。
編輯:Sintax錯誤PD:我現在無法使用,因為我必須在通過IP過濾的Web服務中使用,但VS2010如果我在字典上使用count,告訴我將包含鍵/值對的數量。
如果您正在談論System.Collections.Generic.Dictionary(Of TKey, Of TValue)
,您的代碼將拋出ArgumentException
因為您要多次添加相同的密鑰。
如果您使用索引器,它仍然無法工作:
Rooms(1) = 101
Rooms(1) = 102
...
像這樣,沒有例外,但第二行只會覆蓋第一行中存儲的值。
看來你實際上想要使用Dictionary(Of Integer, Of List(Of Integer))
。 像這樣使用它:
Dim Rooms = Rooms As Dictionary(Of Integer, Of List(Of Integer))
Rooms(1) = New List(Of Integer) From { 101, 102, 109, 110 }
Rooms(2) = New List(Of Integer) From { 103, 104, 105 }
Rooms(3) = New List(Of Integer) From { 106, 107 }
Rooms.Count
將為您提供字典中的鍵數。
如果且僅當您的每個鍵的列表稍后沒有更改時,您可以使用數組而不是List(Of Integer)
實例。
如果將相同的鍵添加到字典中,則會出現異常。 如果這是keyvaluepairs列表,您可以使用groupby linq運算符
Dim rooms = New List(Of KeyValuePair(Of String, String))()
rooms.Add(New KeyValuePair(Of String, String)("one", "thing1"))
rooms.Add(New KeyValuePair(Of String, String)("one", "thing2"))
rooms.Add(New KeyValuePair(Of String, String)("two", "other1"))
rooms.Add(New KeyValuePair(Of String, String)("two", "other2"))
Dim query = rooms.GroupBy(Function(x) x.Key)
For Each g As var In query
Console.WriteLine("Key: " & Convert.ToString(g.Key))
For Each v As var In g
Console.WriteLine(vbTab & Convert.ToString(v.Value))
Next
Next
請回答SO問題c#dictionary如何為單個鍵添加多個值? 在那里我展示了我對多地圖的實現。 這基本上是一個包含列表條目的字典。 它允許您存儲每個鍵的值列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.