How to compare two List and delete repeated fields?

Posted on

Question :

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


Answer :

Assuming that T is the type of your lists:

foreach(T t in lista1) 


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) 

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


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


Leave a Reply

Your email address will not be published. Required fields are marked *