1

I am trying to remove List<int> items from List<int> items2

List<int> item1 = new List<int> {1,2,3,4,5,6,7,8,9,10};
List<int> item2 = new List<int> {1,2,3,4};

After removing the item2 values from item1 the required result is

item1 = {5,6,7,8,9,10 }

Is there any direct method or any other method to remove the contents of one list of items from the content of another list of items, with out using 'for' or 'foreach' ?

Gray
  • 115,027
  • 24
  • 293
  • 354
SRN
  • 59
  • 5

1 Answers1

10

Something somewhere is going to have to loop. You don't have to loop in your source code though. As to what you do... that depends on your requirements.

If you change the types of your variables to List<int> you could use List<T>.RemoveAll:

item1.RemoveAll(x => item2.Contains(x));

Or you could just use LINQ, if you're happy with item1 changing value to refer to a different list:

item1 = item1.Except(item2).ToList();

Note that the above will also make item1 a set of distinct values - if you have any duplicates, they will be removed (even if they're not in item2).

An alternative without the duplicate-removing aspect:

item1 = item1.Where(x => !item2.Contains(x)).ToList();

Or to make it perform better if item2 is large:

var item2Set = new HashSet<int>(item2);
item1 = item1.Where(x => !item2Set.Contains(x)).ToList();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194