2

I have 2 Lists of type string:

  • List1 has items - item1, item2, item3
  • List2 has items - item2, item3

Now I need to compare both lists and remove the duplicated items from List1. The modified List1 should have just one item, which is "item1".

foreach loops may work, but what I want to know is there any inbuilt method which does this?

EDIT

Thanks for the answers guys. I was just thinking what would be the case if I wanted to add the missed out items into the List. So just raised another question similar to this.

Add operation in List<string>

TIA!

Community
  • 1
  • 1
Sandeep
  • 5,581
  • 10
  • 42
  • 62

4 Answers4

10

You could use:

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

(As Marc says, this is O(N*M) - fine if you expect the lists to be very short, but awful if either of them could get big.)

Or if you don't mind it being a new list (rather than modifying the existing one), you could just use:

list1 = list1.Except(list2).ToList();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
10

I suspect the best approach to use here would be to put the second list into a hash first, i.e.

var hash = new HashSet<TheType>(List2);
List1.RemoveAll(hash.Contains);

This avoids having O(n*m) performance, instead being O(n+m)

Example:

List<int> List1 = new List<int> {1,2,3};
List<int> List2 = new List<int> {2,3};

var hash = new HashSet<int>(List2);
List1.RemoveAll(hash.Contains);
// now List1 just has {1}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
3

Use

List1 = List1.Except(List2).ToList();
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
1

I recommend using:

List1 = List1.Except(List2).ToList();
Pierluc SS
  • 3,138
  • 7
  • 31
  • 44