281

I'm trying to figure out how to traverse a generic list of items that I want to remove from another list of items.

So let's say I have this as a hypothetical example

List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();

I want to traverse list1 with a foreach and remove each item in List1 which is also contained in List2.

I'm not quite sure how to go about that as foreach is not index based.

8
  • 1
    You want to remove items in List1 which are also in List2? Apr 30, 2010 at 15:16
  • 1
    What should happen if you have list1 = { foo1 } and list2 = { foo1, foo1 }. Should all copies of foo1 be removed from list2, or just the first?
    – Mark Byers
    Apr 30, 2010 at 15:29
  • 2
    -1 - I have downvoted every answer in this question because I thought they were all wrong, but it appears the question is just asked horribly. Now, I can't change them - apologies. Do you want to remove the items from list1 that exist in list2, or do you want to remove the items from list2 that exist in list1? At the time of this comment, each answer provided will perform the latter.
    – John Rasch
    Apr 30, 2010 at 15:34
  • 7
    @John Rashch, you should be a little less trigger happy on those downvotes. Some of the answers are fairly conceptual and only demonstrate how to achieve what the OP wants without even relating to the lists mentioned in the question. Apr 30, 2010 at 15:39
  • 3
    @Mark - you're right, my fault entirely - that's why I put the comment up here explaining what happened, I was searching for a previous answer I had already had to a similar question in the meantime after my voting and was going to leave comments after I found it - turns out that is not the best process for this!
    – John Rasch
    Apr 30, 2010 at 15:47

11 Answers 11

480

You can use Except:

List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();
List<car> result = list2.Except(list1).ToList();

You probably don't even need those temporary variables:

List<car> result = GetSomeOtherList().Except(GetTheList()).ToList();

Note that Except does not modify either list - it creates a new list with the result.

7
  • 20
    Minor point, but this will produce an IEnumerable<car>, not a List<car>. You need to call ToList() to get a list back. In addition, I believe it should be GetSomeOtherList().Except(GetTheList()).ToList() Apr 30, 2010 at 15:17
  • 12
    You will also need using System.Linq; if you didn't have it before.
    – yellavon
    Mar 11, 2015 at 20:28
  • 1
    Note: list1.Except(list2) will not give same result as list2.Except(list1). The last worked for me.
    – radbyx
    Jan 11, 2016 at 10:43
  • 6
    Just be careful when using Except as this actually performs a set operation, which distincts the resulting list. I was not expecting this behaviour as I am using a List, not a HashSet. Related.
    – logan
    Mar 2, 2016 at 20:27
  • 7
    How come this is the right answer? Sure this might give you what you want in your context, however, "Remove items from one list in another" is certainly not equivalent to a set difference operation, and you should not misinform people by accepting this as the right answer!!!! May 26, 2016 at 3:58
49

You don't need an index, as the List<T> class allows you to remove items by value rather than index by using the Remove function.

foreach(car item in list1) list2.Remove(item);
11
  • 5
    +1, but IMO you should use brackets around the list2.Remove(item); statement.
    – ANeves
    Apr 30, 2010 at 15:18
  • 5
    @sr pt: I always use brackets on statements that appear on another line, but not on single-statement blocks that I can/do place on the same line as the flow control statement. Apr 30, 2010 at 15:19
  • 2
    As long as you're consistent, it doesn't matter if you use brackets or not.. IMO :)
    – Ian P
    Apr 30, 2010 at 15:20
  • 12
    @uriz: Disregarding the qualifications of what would be elegant, this is the only answer that actually does what the question says (removes the items in the main list); the other answer creates a new list, which may not be desirable if the list is being passed in from a different caller that is expecting it to be modified instead of getting a replacement list. Jun 23, 2014 at 14:39
  • 11
    @uriz @AdamRobinson since we're discussing elegant solutions... list1.ForEach(c => list2.Remove(c)); Oct 31, 2014 at 14:43
28

In my case I had two different lists, with a common identifier, kind of like a foreign key. The second solution cited by "nzrytmn":

var result =  list1.Where(p => !list2.Any(x => x.ID == p.ID && x.property1 == p.property1)).ToList();

Was the one that best fit in my situation. I needed to load a DropDownList without the records that had already been registered.

Thank you !!!

This is my code:

t1 = new T1();
t2 = new T2();

List<T1> list1 = t1.getList();
List<T2> list2 = t2.getList();

ddlT3.DataSource= list2.Where(s => !list1.Any(p => p.Id == s.ID)).ToList();
ddlT3.DataTextField = "AnyThing";
ddlT3.DataValueField = "IdAnyThing";
ddlT3.DataBind();
1
24

I would recommend using the LINQ extension methods. You can easily do it with one line of code like so:

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

This is assuming of course the objects in list1 that you are removing from list2 are the same instance.

1
  • 2
    It removes duplicates as well.
    – Incredible
    Sep 19, 2017 at 8:30
18
list1.RemoveAll(l => list2.Contains(l));
3
  • a.k.a. "totally-impure" :-) Jun 22, 2017 at 0:26
  • 1
    What wrong with it. It looks better then creating another list using Except. Especially when both lists are very small. May 9, 2018 at 13:02
  • 2
    Since both list methods are O(N), this will lead to O(N^2) which might be an issue with large lists.
    – tigrou
    Nov 4, 2019 at 16:22
16

You could use LINQ, but I would go with RemoveAll method. I think that is the one that better expresses your intent.

var integers = new List<int> { 1, 2, 3, 4, 5 };

var remove = new List<int> { 1, 3, 5 };

integers.RemoveAll(i => remove.Contains(i));
2
  • 11
    Or even simpler with method groups you can do - integers.RemoveAll(remove.Contains);
    – Ryan
    Apr 17, 2013 at 21:08
  • does this solution faster than the LINQ Except method? or use less ressources? Jul 9, 2020 at 14:00
10

Solution 1 : You can do like this :

List<car> result = GetSomeOtherList().Except(GetTheList()).ToList();

But in some cases may this solution not work. if it is not work you can use my second solution .

Solution 2 :

List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();

we pretend that list1 is your main list and list2 is your secondry list and you want to get items of list1 without items of list2.

 var result =  list1.Where(p => !list2.Any(x => x.ID == p.ID && x.property1 == p.property1)).ToList();
0

As Except does not modify the list, you can use ForEach on List<T>:

list2.ForEach(item => list1.Remove(item));

It may not be the most efficient way, but it is simple, therefore readable, and it updates the original list (which is my requirement).

0

I think it would be quick to convert list A to a dictionary and then foreach the second list and call DictA.Remove(item) otherwise I think most solutions will cause many iterations through list A either directly or under the covers.

If the lists are small, it probably won't matter.

0

In case you have two different list with different DataModals

List<FeedbackQuestionsModel> feedbackQuestionsList = new();

List<EmployeesFeedbacksQuestionsModel> employeeQuestionsList = new();

var resultList = feedbackQuestionsList.Where(p => !employeeQuestionsList.Any(x => x.Question == p.Question)).ToList();
feedbackQuestionsList = resultList.ToList();
-5

Here ya go..

    List<string> list = new List<string>() { "1", "2", "3" };
    List<string> remove = new List<string>() { "2" };

    list.ForEach(s =>
        {
            if (remove.Contains(s))
            {
                list.Remove(s);
            }
        });
1
  • 6
    -1. This will throw an exception after the first item is removed. Also, it's (generally) a better idea to traverse the list to remove, since it's usually smaller. You're also forcing more list traversals doing it this way. Apr 30, 2010 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.