Monday, November 21, 2016

LINQ. Except. Filtering records from set

Let's imagine, you have:

class AppMeta
{
  public int Id {get;set;}
}

var excludedAppIds = new List<int> {2, 3, 5, 6};
var unfilteredApps = new List<AppMeta>
                         {
                           new AppMeta {Id = 1}
                           new AppMeta {Id = 2}
                           new AppMeta {Id = 3}
                           new AppMeta {Id = 4}
                           new AppMeta {Id = 5}
                         }
You need to get a list of AppMeta back that filters on excludedAppIds

Solution:

Add an extension to Except:

public static class ExtensionMethods
{
    public static IEnumerable<TA> Except<TA, TB, TK>(
        this IEnumerable<TA> a,
        IEnumerable<TB> b,
        Func<TA, TK> selectKeyA,
        Func<TB, TK> selectKeyB, 
        IEqualityComparer<TK> comparer = null)
    {
        return a.Where(aItem => !b.Select(bItem => selectKeyB(bItem)).Contains(selectKeyA(aItem), comparer));
    }

then use it something like this:
var filteredApps = unfilteredApps.Except(excludedAppIds, a => a.Id, b => b);



No comments: