Wesley Wesley - 3 months ago 32
C# Question

Filter Linq EXCEPT on properties

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 matches, for example:

var excludes = users.Except(matches);


I want to use exclude to keep my code short and simple, but can't seem to find out how to do the following:

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}
}


How do I get a list of AppMeta back that filters on excludedAppIds?

Answer

Try a simple where query

var filtered = unfilteredApps.Where(i => !excludedAppIds.Contains(i.Id)); 

The except method uses equality, your lists contain objects of different types, so none of the items they contain will be equal!