Insert objects into an Array without copying them

2

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

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 is not working, so it shows in the toAdd list:

MeuObjeto
MeuObjeto
MeuObjeto
MeuObjeto
MeuObjeto
....

and repeating them infinitely, I want to make it not have the same object in the list.

    
asked by anonymous 04.06.2015 / 02:39

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 Any method with the Func(Of TSource, Boolean) parameter returns True if any item in the collection satisfies the passed condition. In this case you need to deny it with Not to invert the condition.

Or, if you prefer, you can use All , so you do not have to deny the method return:

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

All does the inverse of Any , verifying 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, a Distinct is first made. of the strings and then for each a AutocompleteItem object is created with the Select , and then converts to List (I'm assuming that toAdd is List(Of String) ).

    
04.06.2015 / 06:15