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