加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何在VB.net中使用Dictionary?

发布时间:2020-12-16 07:28:16 所属栏目:asp.Net 来源:网络整理
导读:我已经编写了这个函数来自动从字符串数组中的不同值中将性别更正为M或F.它工作正常但我的经理告诉我使用Dictionary,他说效率更高.但我不知道.有谁想帮我理解如何做到这一点?谢谢. Public Function AutoGender(ByVal dt As DataTable) As DataTable Dim Gend
我已经编写了这个函数来自动从字符串数组中的不同值中将性别更正为M或F.它工作正常但我的经理告诉我使用Dictionary,他说效率更高.但我不知道.有谁想帮我理解如何做到这一点?谢谢.

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",{"male",{"man",{"m",{"men",{"guy",{"girl","F"},{"girls",{"female",{"woman",{"f",{"women",{"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","guy"}
Shared femaleSynonyms As New HashSet(Of String) From
    {"girl","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也必须是唯一的,因此它不能包含重复的字符串(如字典中的键),但它不是键值对而只是一组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读