c# – Is there an opposite to `contains`?

Question:

I have a list:

List<int> lista1 = new List<int>();
lista1.Add(1);
lista1.Add(2);
lista1.Add(3);

List<int> lista2 = new List<int>();
lista2.Add(1);
lista2.Add(2);

To get from lista1 the elements that also exist in lista2 just use:

var resultado = lista1.Where(li => lista2.Contains(li)).ToList();

So the result obtained is: { 1 , 2 } .

So far so good, but what if I wanted to get from lista1 the elements that are not in lista2 ?

In this case the result should be { 3 } .

Is it possible to solve this in just one line?

I am using Entity Framework.

Answer:

You are looking for the Except() .

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

I put it on GitHub for future reference .

Scroll to Top