Remove items from a list based on another list

  • Thread starter Thread starter Peter Morris
  • Start date Start date
P

Peter Morris

I remember a post similar to this but cannot find it.

I have

List<string> fileNamesToDelete;
List<SomeObject> objectsToSend;

Let's say fileNamesToDelete has 1,000 items in it, and objectsToSend has 990
items in it. What I want to do is something like this

fileNamesToDelete = fileNamesToDelete.Where(fn =>
!fileNamesToDelete.Contains(fn)).ToList();

But the .Contains is going to be slow. I can create a dictionary<string,
object> to hold the fileNamesToDelete, but I remember there was a LINQ way
of doing this which probably used a dictionary internally anyway. Can
someone remind me what that approach is?


Thanks
 
Peter said:
I remember a post similar to this but cannot find it.

I have

List<string> fileNamesToDelete;
List<SomeObject> objectsToSend;

Let's say fileNamesToDelete has 1,000 items in it, and objectsToSend has
990 items in it. What I want to do is something like this

fileNamesToDelete = fileNamesToDelete.Where(fn =>
!fileNamesToDelete.Contains(fn)).ToList();

That way you would end up with an empty list fileNamesToDelete so the
above is probably not what you want.
 
fileNamesToDelete = fileNamesToDelete
Where fn => fn is not in objectsToSend.FileName


That's what I meant :-)
 
Peter said:
I remember a post similar to this but cannot find it.

I have

List<string> fileNamesToDelete;
List<SomeObject> objectsToSend;

Let's say fileNamesToDelete has 1,000 items in it, and objectsToSend has
990 items in it. What I want to do is something like this

fileNamesToDelete = fileNamesToDelete.Where(fn =>
!fileNamesToDelete.Contains(fn)).ToList();

But the .Contains is going to be slow. I can create a
dictionary<string, object> to hold the fileNamesToDelete, but I remember
there was a LINQ way of doing this which probably used a dictionary
internally anyway. Can someone remind me what that approach is?
fileNamesToDelete = fileNamesToDelete.Except(objectsToSend.Select(o =>
o.FileName)).ToList();

This indeed uses an internal dictionary.
 
Thanks Jeroen

I have gone ahead and used dictionaries now. I will revist the code and use
Except instead. Thanks very much, I will try to remember it for future use!
 
Back
Top