我编写了这个函数来自动将字符串数组中不同值的性别更正为 M 或 F。它工作得很好,但我的经理告诉我使用字典,他说这更有效。但我不知道。有人愿意帮助我了解如何做到这一点吗?谢谢。
Public Function AutoGender(ByVal dt As DataTable) As DataTable
Dim Gender As String = ""
Dim Mkeywords() As String = {"boy", "boys", "male", "man", "m", "men", "guy"}
Dim Fkeywords() As String = {"girl", "girls", "female", "woman", "f", "women", "chick"}
Dim row As DataRow
For Each row In dt.Rows
If Mkeywords.Contains(row("Gender").ToString.ToLower) Then
Gender = "M"
row("Gender") = Gender
ElseIf Fkeywords.Contains(row("Gender").ToString.ToLower) Then
Gender = "F"
row("Gender") = Gender
End If
Next
Return dt
End Function
最佳答案
下面是一个如何实现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
也必须是唯一的,因此它不能包含重复的字符串
(如字典
中的键),但它不是一个键值对,但只是一个集合。
关于asp.net - 如何在VB.net中使用字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11135488/