How to compare lista1
and lista2
, excluding repeated items in one of them?
How to compare lista1
and lista2
, excluding repeated items in one of them?
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.
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
If I understand correctly, with LINQ is the simplest way:
lista2 = list1.Intersect(list2).ToList();