I have two lists. I want to remove any items from LIST1 that are NOT present in LIST2.
So for example:
var list1 = new List<DownloadTask>();
list1.Add(new DownloadTask{ OperationID = 1, MachineID = 1 });
list1.Add(new DownloadTask{ OperationID = 2, MachineID = 1 });
list1.Add(new DownloadTask{ OperationID = 3, MachineID = 1 });
list1.Add(new DownloadTask{ OperationID = 3, MachineID = 2 });
var list2 = new List<DownloadTask>();
list2.Add(new DownloadTask{ OperationID = 1, MachineID = 1 });
list2.Add(new DownloadTask{ OperationID = 3, MachineID = 2 });
After run list1 should contain only items: with combination operationId = 1, machineId = 1 AND OperationId = 3, MachineId =2.
Does
DownloadTaskoverrideEqualsandGetHashCodecorrectly? If so, all you need is:That’s if you’re happy to create a new list, of course. If you really want to remove them from the existing list, it’s slightly harder. It would quite possibly be simplest to work out what the result should look like, then clear and re-add:
Of course, all of this does require you to implement equality appropriately in
DownloadTask– but if you haven’t done so already, it sounds like it would be a good idea to do so. (Or at least implementIEqualityComparer<DownloadTask>somewhere – you can pass a comparer toIntersect.)As a side note, I view “only keep the elements in
list1which are also inlist2” (i.e. intersection) as a simpler way of looking at the problem than “remove all elements fromlist1which aren’t inlist2” – the latter is basically a double negative, which is always a bit of a pain.