Removing items from one collection to another collection

I have two collections (shared lists), call them ListA and ListB.

In ListA, I have several elements of type A. In ListB, I have some elements of type B that have an ID (but not the same type) as the elements in ListA, and many more. I want to remove all elements from listB that have the same identifier as in ListA. What is the best way to do this? Are Linq objects in good shape? Which algorithm would you use?

Example

ListA: ItemWithID1, ItemWithID2¨

ListB: ItemWithID1, ItemWithID2, ItemWithID3, ItemWithID4

EDIT: I forgot to mention in my original question that ListA and ListB do not contain the same types. Thus, the only way to compare them is through the .Id property. This invalidates the answers I have received so far.

+3
source share
6 answers

I found that lambda expressions were the perfect combination. Instead of the long linq to objects method, I could do this with just a few lines with a lambda:

foreach(TypeA objectA in listA){
    listB.RemoveAll(objectB => objectB.Id == objectA.Id);
}
+3
source

Here are two options. Not sure which one is faster.

listB.RemoveAll(listA.Contains);


foreach (string str in listA.Intersect(listB))
  listB.Remove(str);
+12
source

, Microserf's

, . Id , Microserf.

+1

:

for (item i: LISTA) {
    removeItem(i, LISTB);
}


method removeItem(Item, List) {
    for (Item i: List) {
        if (Item == i)
            List.removeItem(i);
    }
}
0

, , ListA, ListB, ListA ListB.contains, ListB.

-

foreach Object o in ListA
  If ListB.contains(o)
    ListB.remove(o)
0

- , C6 Generic Collection Library .NET - RemoveAll, . C5 , RetainAll, , RemoveAll , , ,

ListB.RetainAll(ListA) - { Item1, Item2 }, ListB.RemoveAll(ListA) - { Item3, Item4 }.

0

Source: https://habr.com/ru/post/1698823/


All Articles