简体   繁体   中英

Comparing generic lists and filter mismatching values

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:

var result = bar.Except(foo);

Internally this adds all of foo into a Set<> (internal .Net type analogous to a HashSet<T> ) and then yields all those items from bar which are successfully added.

Note - if you need case-insensitive comparison you can pass a specific StringComparer :

var result = bar.Except(foo, StringComparer.OrdinalIgnoreCase);

The result is an IEnumerable<string> and, as with many of the other Linq extension methods, doesn't start doing anything until you iterate with foreach or 'realise' the result with a call to ToArray or ToList or whatever.

If you don't want to use Except twice, consider something like this:

var listOld = new SortedSet<string> { "1", "2", "3", "4", };
var listNew = new SortedSet<string> { "1", "1½", "2", "4", "5", };

Then simply saying

listNew.SymmetricExceptWith(listOld);

will modify listNew so it now contains the "difference elements" between the two original lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM