Coder Perfect

Delete things from one list and add them to another.

Problem

I’m attempting to find out how to go through a generic list of objects and remove them from another list.

So, let’s pretend I’m using this as an example.

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

I want to use a foreach loop to explore List1 and remove any items in List1 that are already in List2.

Because foreach isn’t index-based, I’m not sure how to go about it.

Asked by PositiveGuy

Solution #1

Except: may be used.

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

Those temporary variables are probably unnecessary:

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

Except does not change either list; instead, it generates a new one containing the result.

Answered by Mark Byers

Solution #2

You don’t need an index because the Delete function in the ListT> class allows you to remove items by value rather than index.

foreach(car item in list1) list2.Remove(item);

Answered by Adam Robinson

Solution #3

I recommend that you use the LINQ extension techniques. It’s simple to do with just one line of code, as seen below:

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

Of course, this assumes that the objects in list1 that you’re deleting from list2 are of the same type.

Answered by Berkshire

Solution #4

In my scenario, I had two separate lists that shared a common identity, similar to a foreign key. “nzrytmn” proposes a second solution:

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

Was the one that best suited my needs. I needed to load a DropDownList without the previously registered records.

Thank you !!!

My code looks like this:

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();

Answered by Gabriel Santos Reis

Solution #5

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

Answered by Alexandre Castro

Post is based on https://stackoverflow.com/questions/2745544/remove-items-from-one-list-in-another