Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Linq EXCEPT on properties

Tags:

c#

linq

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?

like image 573
Wesley Avatar asked Mar 21 '13 06:03

Wesley


People also ask

How Except works in LINQ?

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.

Where and Except LINQ C#?

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.

What does except do in C#?

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.

What allows adding some conditional filters to the query in LINQ?

You can add additional Where constraints based on a condition in two ways: With a lambda expression. With WhereIf extenstion method.


2 Answers

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!

like image 65
ColinE Avatar answered Sep 19 '22 20:09

ColinE


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); 
like image 24
dotNET Avatar answered Sep 17 '22 20:09

dotNET