下面是一個例子,你如何可以實現Dictionary(Of String, String)
查找這個代名詞是已知還是不:
Shared GenderSynonyms As Dictionary(Of String, String) = New Dictionary(Of String, String) From
{{"boy", "M"}, {"boys", "M"}, {"male", "M"}, {"man", "M"}, {"m", "M"}, {"men", "M"}, {"guy", "M"},
{"girl", "F"}, {"girls", "F"}, {"female", "F"}, {"woman", "F"}, {"f", "F"}, {"women", "F"}, {"chick", "F"}}
Public Function AutoGender(ByVal dt As DataTable) As DataTable
If dt.Columns.Contains("Gender") Then
For Each row As DataRow In dt.Rows
Dim oldGender = row.Field(Of String)("Gender").ToLower
Dim newGender As String = String.Empty
If GenderSynonyms.TryGetValue(oldGender, newGender) Then
row.SetField("Gender", newGender)
End If
Next
End If
Return dt
End Function
請注意,我用的collection initializer填補Dictionary那就是使用一種方便的方法文字初始化集合。您也可以使用Add
method。
編輯:只是另一種方法可能是使用兩個HashSet(Of String)
,一個爲男性同義詞和一個針對女性更簡潔:
Shared maleSynonyms As New HashSet(Of String) From
{"boy", "boys", "male", "man", "m", "men", "guy"}
Shared femaleSynonyms As New HashSet(Of String) From
{"girl", "girls", "female", "woman", "f", "women", "chick"}
Public Function AutoGender(ByVal dt As DataTable) As DataTable
If dt.Columns.Contains("Gender") Then
For Each row As DataRow In dt.Rows
Dim oldGender = row.Field(Of String)("Gender").ToLower
Dim newGender As String = String.Empty
If maleSynonyms.Contains(oldGender) Then
row.SetField("Gender", "M")
ElseIf femaleSynonyms.Contains(oldGender) Then
row.SetField("Gender", "F")
End If
Next
End If
Return dt
End Function
一個HashSet
也必須是唯一的,所以它不能包含重複Strings
(如Dictionary
中的密鑰),但它不是鍵值對,而只是一組值。
也許這可以幫助http://www.dotnetperls.com/dictionary-vbnet – Bishan