Remove items from a list based on another list

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
 
M

Martin Honnen

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.
 
P

Peter Morris

fileNamesToDelete = fileNamesToDelete
Where fn => fn is not in objectsToSend.FileName


That's what I meant :)
 
J

Jeroen Mostert

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.
 
P

Peter Morris

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top