I would like to compare to generic lists, and filter the mismatching values. I’m currently using a foreach loop, but I would like to know if there is a way to solve this using a lambda expression? In the example below i would like a resulting list that only contains the “4”.
List<string> foo = new List<string>() { "1", "2", "3" };
List<string> bar = new List<string>() { "1", "2", "3", "4" };
Use the Linq
Except<>extension:Internally this adds all of
foointo aSet<>(internal .Net type analogous to aHashSet<T>) and then yields all those items frombarwhich are successfully added.Note – if you need case-insensitive comparison you can pass a specific
StringComparer:The result is an
IEnumerable<string>and, as with many of the other Linq extension methods, doesn’t start doing anything until you iterate withforeachor ‘realise’ the result with a call toToArrayorToListor whatever.