Filter Linq EXCEPT on properties

前端 未结 8 1291
南方客
南方客 2020-12-04 17:45

This may seem silly, but all the examples I\'ve found for using Except in linq use two lists or arrays of only strings or integers and filters them based on the

相关标签:
8条回答
  • 2020-12-04 18:27

    Construct a List<AppMeta> from the excluded List and use the Except Linq operator.

    var ex = excludedAppIds.Select(x => new AppMeta{Id = x}).ToList();                           
    var result = ex.Except(unfilteredApps).ToList();
    
    0 讨论(0)
  • 2020-12-04 18:30

    I use an extension method for Except, that allows you to compare Apples with Oranges as long as they both have something common that can be used to compare them, like an Id or Key.

    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);
    

    the extension is very similar to ColinE 's answer, it's just packaged up into a neat extension that can be reused without to much mental overhead.

    0 讨论(0)
提交回复
热议问题