Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items in one IList<> from another IList<> [duplicate]

Sorry to post such basic questions, I'm new to LINQ and am trying to figure out the best way to do this short of looping through each IList.

I have 2 ILists<> with of custom dto objects. I want to remove all the matching items from on list that are in the other.

IList<ItemDTO> list1 = itemsbl.GetBestItems();
IList<ItemDTO> list2 = itemsbl.GetWorstItems();

I need to remove all the items in list1 from list2. I have been looking at the Except() method but apparently i need my ItemsDTO class to override the GetHashCode and Equals methods for that to work, but i am having trouble finding some examples of this.

Could someone please show me the best way to remove list1 from list2?

Thanks again

like image 226
Nugs Avatar asked Feb 15 '12 22:02

Nugs


3 Answers

You can probably use the Except method to do this.

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

If you want to replace list2 then just do this:

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

From MSDN:

To compare custom data types, implement the IEquatable generic interface and provide your own GetHashCode and Equals methods for the type. The default equality comparer, Default, is used to compare values of types that implement IEquatable.

like image 136
Dismissile Avatar answered Oct 31 '22 11:10

Dismissile


var list1 = new List<string> { "A", "B", "C" };
var list2 = new List<string> { "A", "C", "E", "B", "D", "G", "F" };
list2.RemoveAll(list1.Contains);

will work, too. Note that the list1.Contains is actually a lambda

s => list1.Contains(s)

-A.

like image 33
Ani Avatar answered Oct 31 '22 13:10

Ani


Hash it definitely a good way, @Jon Skeet below answer to a similar question will provide you with the solution.

so basically the syntax is:

 var setToRemove = new HashSet<ItemDTO>(list1);
 list2.RemoveAll(x => setToRemove.Contains(x));

Using LINQ to remove elements from a List<T>

hopefully this helps.

like image 1
Nickz Avatar answered Oct 31 '22 12:10

Nickz