user3844416 user3844416 - 6 months ago 28
Vb.net Question

check if a textbox value already exists in a listbox

I have a ListBox bound to a observableCollection of "widgets". Each widget in the collection only has a name field at the moment but that will change.

On the window I have a text box where a user can enter another name for addition to the observableCollection.

Each entry has to be unique.

At the moment I use this

Dim query As IEnumerable(Of clsWidget)
query = WidgetSource.Where(Function(widget) widget.name = txtNewName.Text)

If query.Count > 0 Then
Debug.Print("Tried to add a widget that already in the collection")
End If


Is there a more efficient way of doing this?

Answer

It can be more efficiently coded by using the code below which only requires one line.

    If WidgetSource.Any(Function(widget) widget.name = txtNewName.Text) Then Debug.Print("Tried to add a widget that already in the collection")

If by efficient you mean it runs faster then I doubt there will be much difference between my code and yours.