Reputation: 3579
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
Reputation: 11
var NewList = FirstList.Where(a => SecondList.Exists(b => b.ID != a.ID));
Using LINQ
Upvotes: 0
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
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
Reputation: 60448
I think you mean the generic type List<Type>
. You can use Linq
to do this
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));
Upvotes: 2
Reputation: 79909
Using LINQ you can do this:
List1.RemoveAll(i => !List2.Contains(i));
Upvotes: 1