Home > database >  vb.net list<T> if not exist add
vb.net list<T> if not exist add

Time:12-02

I have a List

    Public Class Connoisseur
                Public Name As String
                Public Pieces As String
    End Class


Private Sub Button26_Click(sender As Object, e As RibbonControlEventArgs) Handles Button26.Click
    Dim CS As New List(Of Connoisseur)()
End Sub

How to use generics Write an IFNotExistsAdd function

CS = {"test1","2"}

It looks like this

CS.IFNotExistsAdd(New Connoisseur() With{.Name="test1",.Pieces="1"}) 'This line will not be added because CS.Name already contains "test1"
CS.IFNotExistsAdd(New Connoisseur() With{.Name="test2",.Pieces="1"})

The output looks like this

Output:

{"test1","2"}
{"test2","1"}

CodePudding user response:

You're question is not entirely clear. IFNotExistsAdd is not a valid method name for a List, so you have to create an extension method.

Create a Module (using the same namespace as the calling class)

Module Extensions

<Extension>
Public Sub IFNotExistsAdd(Of T)(list As List(Of T), item As T)
    If Not list.Any(Function(x) x.Equals(item)) Then
        list.Add(item)
    End If
End Sub

End Module

Then you need to add an Equals override to the class (I've also added an initialiser for the properties)

Public Class Connoisseur

Public Name As String
Public Pieces As String

Public Sub New(name As String, pieces As String)
    Me.Name = name
    Me.Pieces = pieces
End Sub

Public Overrides Function Equals(obj As Object) As Boolean
    If TypeOf obj Is Connoisseur Then
        Return EqualsItem(CType(obj, Connoisseur))
    Else
        Return False
    End If
End Function

Public Function EqualsItem(obj As Connoisseur) As Boolean
    Return obj.Name = Me.Name And obj.Pieces = Me.Pieces
End Function

End Class

You can then run add items to the list and it will only add those that are unique

CS.IFNotExistsAdd(New Connoisseur("test1", 1))
CS.IFNotExistsAdd(New Connoisseur("test1", 1))
CS.IFNotExistsAdd(New Connoisseur("test2", 2))

This will only add test1 and test2.

  • Related