Insert objects into an Array without copying them

Asked

Viewed 34 times

2

Is there any way I can put the items in one Array without multiplying them? I am trying the following. I want to add the list items MethodList on the list toAdd, but without repeating what is on the list sourceItems:

For Each iKey As String In MethodList
     For Each d As AutocompleteItem In mMenu.Items.sourceItems
        If Not (d.Text = iKey) Then ' Verifica se o item não existe na lista
           toAdd.Add(New AutocompleteItem(text:=iKey, 7))
        End If
     Next
Next

But it’s not working, it’s showing like this on the list toAdd:

MeuObjeto
MeuObjeto
MeuObjeto
MeuObjeto
MeuObjeto
....

and repeating them endlessly, I want to make sure you don’t have the same object on the list.

  • You can do something like this: If Not (mMenu.Items.sourceItems.contains(iKey)) Then

  • Doesn’t work. sourceItems is a list of Autocompleteitem, the object iKey is a String, would give a conflict.

1 answer

1


You can use the extension method Any of System.Linq, as follows:

For Each iKey As String In MethodList
    If Not toAdd.Any(Function(x) x.Text = iKey) Then
        toAdd.Add(New AutocompleteItem(text:=iKey, 7))
    End If
Next

The method Any with the parameter Func(Of TSource, Boolean), returns True if any item in the collection meets the condition passed. In that case you need to deny it with the Not to reverse the condition.


Or, if you prefer, you can use the All, not to deny the return of the method:

For Each iKey As String In MethodList
    If toAdd.All(Function(x) x.Text <> iKey) Then 
        toAdd.Add(New AutocompleteItem(text:=iKey, 7))
    End If
Next

The Alldoes the reverse of Any, checking that all items in the collection satisfy the condition. In this case, if all are different, then your item does not exist in the list.


One more option, for those who like to save lines:

toAdd = MethodList.Distinct().Select(Function(x) New AutocompleteItem(x, 7)).ToList()

In this alternative, first is made a Distinct of the strings and then for each one an object is created AutocompleteItem with the Select and then converts to List (I’m guessing that toAdd is a List(Of String)).

  • That’s exactly what it was! Hug man ^-^.

  • I’ve added one more alternative, if you prefer.

  • The first worked perfectly.

  • 1

    Okay, and I believe I perform better than the last one. I’m leaving alternatives because it can help other people.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.