How to use Linq Lambda Expression IEqualityComparer For IEnumerable.Except

One of the thing that sometimes annoys is Lambda Expression with IEqualityComparer. I was trying to pick items with Except Comparer from the list. After doing quick search on google found the below extension method which can be used in such scenario. 

public static IEnumerable Except(this IEnumerable first, IEnumerable second, Func<TSource, TSource, bool> comparer)
return first.Where(x => second.Count(y => comparer(x, y)) == 0);

How to use:

List myItemsList = source.Except(myDeals, (x, y) => x.ID == y.ID).Take(requiredCount).ToList();

This will return the list of items except item(s) which match with an ID in myDeals. 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.