Filter Linq EXCEPT on properties

前端 未结 8 1330
南方客
南方客 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:25

    I like the Except extension methods, but the original question doesn't have symmetric key access and I prefer Contains (or the Any variation) to join, so with all credit to azuneca's answer:

    public static IEnumerable Except(this IEnumerable items,
        IEnumerable other, Func getKey) {
    
        return from item in items
            where !other.Contains(getKey(item))
            select item;
    }
    

    Which can then be used like:

    var filteredApps = unfilteredApps.Except(excludedAppIds, ua => ua.Id);
    

    Also, this version allows for needing a mapping for the exception IEnumerable by using a Select:

    var filteredApps = unfilteredApps.Except(excludedApps.Select(a => a.Id), ua => ua.Id);
    

提交回复
热议问题