Is there an opposite for 'contains'?

16

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 elements that also exist in lista2 just use:

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

So the result is: { 1 , 2 } .

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

In case the result should be { 3 } .

Can this be solved in just one row?

I'm using Entity Framework.

    
asked by anonymous 12.08.2015 / 21:54

2 answers

22

You're looking for Except() .

var resultado = lista1.Except(lista2).ToList();
    
12.08.2015 / 21:59
20

You can do:

var resultado = lista1.Where(li => !lista2.Contains(li)).ToList();
    
12.08.2015 / 21:56