How to remove each item that appears in first collection from second collection using linq?

StackOverflow https://stackoverflow.com/questions/18551690

  •  26-06-2022
  •  | 
  •  

Frage

Suppose I have 2 collections:

1) {1, 2, 3, 5}
2) {2, 5}

I want to remove each item that appears in second collection from first collection, so I will get:

{1, 3}

Questions:

  1. How can I do this with Join OP (better with extension methods syntax)?
  2. And is there any way I can iterate over two collections as I do with nested for/foreach loops?

Edits:
To iterate over two collections simultaneously You can use nested from clauses:

from boy in boys
from girl in girls
select boy + "+" + girl

First time I found this syntax necessary :)

War es hilfreich?

Lösung

This does what you need

var solution = list1.Except(list2);

You can find more details about Except here, but the basic idea is:

This method returns those elements in first that do not appear in second. It does not also return those elements in second that do not appear in first.

Andere Tipps

Easy. Use Except

var newList = list1.Except(list2).ToList();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top