ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

AddIfNotExists

An extension method for adding a value to a collection if it not exists yet.

Source

<Extension>
Public Sub AddIfNotExists(Of T)(list As ICollection(Of T), value As T)
    If Not list.Contains(value) Then
        list.Add(value)
    End If
End Sub

Example

Dim exampleList As List(Of Long) From {1, 3} 

'Value will not be added because value exists
exampleList.AddIfNotExists(1)

'Value will be added because value not exists
exampleList.AddIfNotExists(2)

'Values in list: 1, 2 3

Author: Nick Nijenhuis

Submitted on: 29 jan. 2015

Language: VB

Type: ICollection

Views: 4614