Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items from list that intersect on property using Linq

Tags:

c#

linq

I have 2 lists of different objects (foo & bar) that share the same property lets call it id.

public List<foo> foo { get; set; }
public List<bar> bar { get; set; }

I want to remove all objects from foo that have an id that does not exist in bar

How can this be done in linq? I have been looking at Intersect, RemoveAll & Join but cannot find any example where the lists are of a different type.

like image 734
ojhawkins Avatar asked Oct 04 '13 07:10

ojhawkins


2 Answers

Try this:

foo.RemoveAll(x=> !bar.Any(y=>y.Id==x.Id));

!bar.Any(y=>y.Id==x.Id) will get if item is in bar collection and if it's not it will remove it from foo collection.

Better solution using hashset O(n):

var idsNotToBeRemoved = new HashSet<int>(bar.Select(item => item.Id));                     
foo.RemoveAll(item => !idsNotToBeRemoved.Contains(item.Id));

source of second answer: https://stackoverflow.com/a/4037674/1714342

EDIT:

as @Carra said, first solution is good for small lists and second is more efficient for big lists.

like image 121
Kamil Budziewski Avatar answered Oct 21 '22 21:10

Kamil Budziewski


var foo = foo.Where(f => !bar.Any(b => b.Id == f.Id)).ToList();

Just keep in mind that this is a O(n²) solution, it won't work very well for big lists.

like image 8
Carra Avatar answered Oct 21 '22 21:10

Carra