-3

I am trying to compare every value of one list against every value of another list and then remove any matching values and currently have this code.

foreach (item s in List1)
        {
            for (int i = 0; i < list2.count; i++)
            {
                if (list2.ElementAt(i)==s)
                {
                    list2.Remove(list2.ElementAt(i));
                    continue;
                }                   
            }
        }

There has to be a faster or at the very least, a less intensive method of performing a comparison like this. A faster method is required as this could be used to compare lists which exceed 1000 values each. Any help would be much apreciated

aguertin
  • 496
  • 4
  • 18
Tom Rodd
  • 53
  • 1
  • 6
  • Actually the requirement is to remove the elements from `list2` which are existing in `list1`, isn't it? – sujith karivelil Mar 30 '16 at 02:19
  • As @un-lucky pointed out there are better way to do what you probably need... To make your code faster (not *better* as there existing methods in .NEt to do that) - use dictionary to speed up search. Probably duplicate of http://stackoverflow.com/questions/5636438/difference-between-two-lists. You may want to read [Set operations](https://msdn.microsoft.com/en-us/library/bb546153.aspx) to improve question. – Alexei Levenkov Mar 30 '16 at 02:23
  • 3
    Your question and your code do not match. Your question is about comparing all pairs of elements in two lists. Your code is about removing all the elements of one list from another. Those are *completely different problems*, and you are thoroughly conflating them. Both have efficient solutions, but they are *different* solutions, so *say what you really want*. – Eric Lippert Mar 30 '16 at 02:34

2 Answers2

1

Use Except, it produces difference of two sequences by using the default equality comparer.

Except extension method uses a HashSet<T> which produces O(1) access in LookUp.

list2 = list2.Except(list1).ToList();
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

You want to remove all elements from list2 that are contained in list1. An efficient way would be to create a HashSet that will contain a reference to every object in list1, because lookups against a HashSet are very fast. Then iterate over each element in list2, but in reverse order. This is important because you'll be removing elements. Try something like this:

List<MyObjType> list1 = new List<MyObjType>();
List<MyObjType> list2 = new List<MyObjType>();

HashSet<MyObjType> list1Hashset = new HashSet<MyObjType>(list1);
for (int i = list2.Count - 1; i >= 0; i--)
{
    if (list1Hashset.Contains(list2[i]))
        list2.RemoveAt(i);
}
Serge
  • 3,986
  • 2
  • 17
  • 37