我在VB.Net中有此問題。列表中的重複項
我有一個字符串類型的列表。
Dim list As New List(Of String)
此列表可能包含或不包含重複項。
現在我想要的是,可以說這個列表的值是{「10」,「10」,「10」,「11」,「11」,「12」}
我想創建一個Array(2-三維)/列表,這會給我這樣的價值。
(3,10;(2,11);(1,12)
簡單的意思是存在3次,11次存在2次,12次存在1次。
因爲我使用VB.Net 2.0
我在VB.Net中有此問題。列表中的重複項
我有一個字符串類型的列表。
Dim list As New List(Of String)
此列表可能包含或不包含重複項。
現在我想要的是,可以說這個列表的值是{「10」,「10」,「10」,「11」,「11」,「12」}
我想創建一個Array(2-三維)/列表,這會給我這樣的價值。
(3,10;(2,11);(1,12)
簡單的意思是存在3次,11次存在2次,12次存在1次。
因爲我使用VB.Net 2.0
在.NET 2,你必須這樣跟蹤自己。最簡單的方法很可能會建立自己的Dictionary(Of String, Integer)
存儲計數和手動循環:您需要使用Dictionary(Of String, Integer)
保存每個唯一值的計數
Dim dict = New Dictionary(Of String, Integer)
For Each value in list
If dict.ContainsKey(value) Then
Dim count = dict(value)
dict(value) = count + 1
Else
dict(value) = 1
End If
Next
' dict now contains item/count
For Each kvp in dict
Console.WriteLine("Item {0} has {1} elements", kvp.Key, kvp.Value)
Next
爲什麼不使用字典請不要潛水我任何答覆LINQ
:
Dim lookup As New Dictionary(Of String, Integer)
For Each sz As String In list
If Not lookup.ContainsKey(sz) Then lookup.Add(sz, 0)
lookup(sz) += 1
Next
,像這樣:
Dim dict As New Dictionary(Of String, Integer)
For Each item As String In list
If dict.ContainsKey(item) Then
dict(item) += 1
Else
dict.Add(item, 1)
End If
Next
現在你可以遍歷字典和使用效果,像這樣:
For Each result As String In dict.Keys
' Do something with result
Next
可我通過這本字典對象作爲參數的功能及使用方法的結果呢?如果是的話,那麼你能幫我解決僞代碼問題嗎? – user2322507
@ user2322507是的 - 只需將一個接受「Dictionary(Of String,Integer)」的函數作爲參數,並使用它。 –
謝謝了:) – user2322507