Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting items from one collection in another collection

I've got two collections (generic Lists), let's call them ListA and ListB.

In ListA I've got a few items of type A. In ListB I've got some items of type B that have the SAME ID (but not same type) as the items in ListA, plus many more. I want to remove all the items from ListB that have the same ID as the ones in ListA. What's the best way of doing this? Is Linq to objects a nice fit? What 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 doesn't contain the same types. So the only way to compare them is through the .Id property. Which invalidates the answers I've gotten so far.

like image 973
Peter Evjan Avatar asked Oct 28 '08 18:10

Peter Evjan


People also ask

What is the best way to remove multiple items from a list?

Provided the requirement are to remove more than one item from the collection, this is the best way to go about doing it. For a simple List structure the most efficient way seems to be using the Predicate RemoveAll implementation. Eg.

How do I remove items from an assignment collection?

If you're downloading the assignments one time (e.g., when the app runs), you could translate the collection on the fly into a hashtable where: If you do this, then when you want to remove an item by short name, all you need to do is remove the item from the hashtable by key.

How do I delete missing items from a collection?

'Missing' items from a collection are not considered to be deleted. So what you'll need to do is mark the items for deletion yourself. Something like this:

How to remove all elements from a collection using query?

var subCollection = collection1.RemoveAll (w => collection2.Any (q => q.Name == w.Name)); This query will remove all elements from collection1 if Name match any element Name from collection2


2 Answers

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

listB.RemoveAll(listA.Contains);


foreach (string str in listA.Intersect(listB))
  listB.Remove(str);
like image 87
Todd White Avatar answered Oct 27 '22 12:10

Todd White


I discovered that lambda expressions was a perfect match. Instead of a long linq to objects method, I could do it in just a few lines with lambda:

foreach(TypeA objectA in listA){
    listB.RemoveAll(objectB => objectB.Id == objectA.Id);
}
like image 33
Peter Evjan Avatar answered Oct 27 '22 11:10

Peter Evjan