How to compare two List and delete repeated fields?

3

How to compare lista1 and lista2 , excluding repeated items in one of them?

    
asked by anonymous 09.01.2017 / 14:45

3 answers

7

Assuming that T is the type of your lists:

foreach(T t in lista1) 
{
    if(lista2.Contains(t))
        lista2.Remove(t);
}

EDIT:

According to documentation , you do not need to verify that the item exists before removing. You can remove it directly. It will not make any mistake. You can do this:

foreach(T t in lista1) 
{
    lista2.Remove(t);
}

If t does not exist in lista2 nothing will happen.

    
09.01.2017 / 14:50
4

If what you want are the elements of list 2 that do not exist in list 1, use the Except :

var notInList1 = lista2.Except(lista1).ToList();

Example:

lista 1 => 1, 2, 3, 4
lista 2 => 1, 3, 4, 5, 6

notInList1 => 5, 6
    
09.01.2017 / 15:25
3

If I understand correctly, with LINQ is the simplest way:

lista2 = list1.Intersect(list2).ToList();
    
09.01.2017 / 15:16