Wild Goat
Wild Goat

Reputation: 3579

Remove elements from one List<T> that are found in another

I have two lists

 List<T> list1 = new List<T>();
 List<T> list2 = new List<T>();

I want remove all elements from list1, which also exist in list2. Of course I can loop through the first loop looking for each element in list2, but I am looking for elegant solution.

Thanks!

Upvotes: 20

Views: 29753

Answers (8)

Edev
Edev

Reputation: 11

        var NewList = FirstList.Where(a => SecondList.Exists(b => b.ID != a.ID));

Using LINQ

Upvotes: 0

romanoza
romanoza

Reputation: 4862

If you want to remove a list of objects (list2) from another list (list1) use:

list1 = list1.Except(list2).ToList()

Remember to use ToList() to convert IEnumerable<T> to List<T>.

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126804

To change the actual list1 in place, you could use

list1.RemoveAll(item => list2.Contains(item));

You might instead prefer to simply have a query over the lists without modifying either

var result = list1.Except(list2);

LukeH makes a good recommendation in the comments. In the first version, and if list2 is particularly large, it might be worth it to load the list into a HashSet<T> prior to the RemoveAll invocation. If the list is small, don't worry about it. If you are unsure, test both ways and then you will know.

var theSet = new HashSet<YourType>(list2);
list1.RemoveAll(item => theSet.Contains(item));

Upvotes: 43

Alexander R
Alexander R

Reputation: 2476

var result = list1.Except(list2);

Upvotes: 2

dknaack
dknaack

Reputation: 60448

Description

I think you mean the generic type List<Type>. You can use Linq to do this

Sample

List<string> l = new List<string>();
List<string> l2 = new List<string>();

l.Add("one");
l.Add("two");
l.Add("three");

l2.Add("one");
l2.Add("two");
l2.Add("three");
l2.Add("four");

l2.RemoveAll(x => l.Contains(x));

More Information

Upvotes: 2

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79909

Using LINQ you can do this:

 List1.RemoveAll(i => !List2.Contains(i));

Upvotes: 1

k.m
k.m

Reputation: 31454

With LINQ:

var result = list1.Except(list2);

Upvotes: 8

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

list1.RemoveAll( item => list2.Contains(item));

Upvotes: 6

Related Questions