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
?
The Except() method requires two collections. It returns a new collection with elements from the first collection which do not exist in the second collection (parameter collection). Except extension method doesn't return the correct result for the collection of complex types.
What is LINQ Except in C#? The LINQ Except Method in C# is used to return the elements which are present in the first data source but not in the second data source. There are two overloaded versions available for the LINQ Except Method as shown below.
The Except operator returns the set difference. Or in other words, we can say that it returns the set or collection which contain the elements that do not appear in the second collection or set. It does not support Query Syntax in C# and VB.Net languages.
You can add additional Where constraints based on a condition in two ways: With a lambda expression. With WhereIf extenstion method.
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!
ColinE's answer is simple and elegant. If your lists are larger and provided that the excluded apps list is sorted, BinarySearch<T>
may prove faster than Contains
.
EXAMPLE:
unfilteredApps.Where(i => excludedAppIds.BinarySearch(i.Id) < 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With