18
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 the lista1
the elements that also exist in the lista2
just use:
var resultado = lista1.Where(li => lista2.Contains(li)).ToList();
Thus the result obtained is: { 1 , 2 }
.
So far so good, but what if I wanted to get lista1
the elements that nay are in the lista2
?
In this case the result should be { 3 }
.
It is possible to resolve this in just one line?
I’m using Entity Framework.
Much nicer that way! But it doesn’t work inside the Where, I had to use it as follows:
var resultado = lista1.Except(lista2).ToList();
. Correct there that I accept yours as solution...– Jedaias Rodrigues
It’s true, I went straight to your example, I went to test now and did not give :) Fixed. Alias, I have doubts if your using
Contains()
is the right way to use, although possible.– Maniero
Only one note:
Except
is a joint operation and therefore eliminates duplicates. Iflista1
contain{1,2,3,3}
the result will be just{3}
.– dcastro