列表 - 仅在GUID不存在时插入

时间:2017-07-07 21:33:25

标签: vb.net list

在我将一个项目添加到我的List(Of clsUser)之前,我检查列表中是否存在具有相同GUID的clsUser。

目前我检查这样的存在:

Public Function GUIDExists(ByRef uList As List (Of clsUser), ByVal uGUID As String) As Boolean

    For Each nItem As clsUser In uList
        If nItem.GUID = uGUID Then
            Return True
        End If
    Next

    Return False

End Function

我非常希望简化它并将此检查添加到List(Of clsUser)中,这样我就不必一遍又一遍地编写相同的代码。

有些像MyList.AddIfGUIDDoesntExists(nNewUser)

这可能吗? 如果是的话,有人能告诉我这是怎么做的吗?

1 个答案:

答案 0 :(得分:2)

Imports System.Runtime.CompilerServices    

Public Module ExtensionMethods
    <Extension()> 
    Public Sub AddIfGUIDDoesntExists(ByRef inputList As List(Of clsUser), _
             ByVal item As clsUser)
        Dim contains As Boolean = False
        For Each i As clsUser In inputList
            If (i.GUID = item.GUID) Then
                 contains = True
                 Exit For
            End If
        Next
        If Not contains
            inputList.Add(item)
        End If
    End Sub
End Module

用法:

MyList.AddIfGUIDDoesntExists(nNewUser)