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.
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.
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.
'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:
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
Here are two options. Not sure which one is faster.
listB.RemoveAll(listA.Contains);
foreach (string str in listA.Intersect(listB))
listB.Remove(str);
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With