vb.net 列表< T>如果不存在则添加

hkmswyz6  于 2022-12-05  发布在  .NET
关注(0)|答案(1)|浏览(151)

我有一个列表

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

如何使用泛型编写IFNotExistsAdd函数

CS = {"test1","2"}

它看起来像这样

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"})

输出如下
输出量:

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

u5rb5r591#

您的问题并不完全清楚。IFNotExistsAdd 不是List的有效方法名,因此您必须创建一个扩展方法。
创建模块(使用与调用类相同的命名空间)

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

然后,您需要向类添加Equals覆盖(我还为属性添加了初始化程序)

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

然后,您可以运行“将项目添加到列表”,它将只添加那些唯一的项目

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

这将只添加test1和test2。

相关问题