iAteABug_And_iLiked_it
iAteABug_And_iLiked_it

Reputation: 3795

How to filter a list based on another list using Linq?

I have these two lists, one a list of Venue Objects, one a list of BlockedVenues objects.

I need to filter each item in the listOfAllVenues so that it doesn't contain any venue that is blocked

     IQueryable<Venue> listOfAllVenues = MyDB.Venues;
     IQueryable<BlockedVenue> listOfBlockedVenues = Mydb.BlockedVenue;
     //I need something to accomplish this please
     // var listOfAllVenues_WithoutBlocked_Venues = 
                           ( Select All venues from listOfAllVenues
                             where listOfAllVenues.ID is NOT in
                             listOfBlockedVenues.VenueID)

Please note that yes both list types are different, but listOfAllVenues has an int ID field, and listOfBlockedVenues has a VenueID int field, i need to use these two

Many Thanks

Upvotes: 64

Views: 113650

Answers (2)

Brian Bargas
Brian Bargas

Reputation: 31

As of NET 6, you can use ExceptBy.

var filtered = allVenues.ExceptBy(blockedVenues.Select(x => x.VenueID), venue => venue.ID);

This will get all venues except those whose ID is in blockedVenues.Select(x => x.VenueID)

https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.exceptby?view=net-6.0

Upvotes: 3

Kamil Budziewski
Kamil Budziewski

Reputation: 23107

Try this:

var filtered = listOfAllVenues
                   .Where(x=>!listOfBlockedVenues.Any(y=>y.VenueId == x.Id));

It will get all Venues where Id is not in blockedVenues list

Upvotes: 124

Related Questions