Is there an opposite for `contains`?

Asked

Viewed 484 times

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.

2 answers

23


  • 1

    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...

  • 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.

  • 5

    Only one note: Except is a joint operation and therefore eliminates duplicates. If lista1 contain {1,2,3,3} the result will be just {3}.

21

You can do:

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

    How did I not think of it before?! rsrsrs... Thank you very much! 100% solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.