61

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

5
  • 1
    So you want everything from listOfAllVenues Except the ones in listOfBlockedVenues?
    – Corak
    Sep 24, 2013 at 9:37
  • 1
    @Corak yep, but types are different Sep 24, 2013 at 9:37
  • @Corak yes exactly :) types are different, true but listOfAllVenues has an int ID field, and listOfBlockedVenues has a VenueID int field, i need to use these two Sep 24, 2013 at 9:37
  • Ah, different types (why? o_O), too bad. So @wudzik s answer. ^_^
    – Corak
    Sep 24, 2013 at 9:39
  • Do Venue and BlockedVenue have a common base type? Sep 24, 2013 at 9:39

2 Answers 2

119

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

3
  • 8
    simplified: var filtered = listOfAllVenuses.Where(x=>listOfBlockedVenues.All(y=>y.VenueId != x.Id));
    – Roman Y
    Jun 26, 2015 at 23:20
  • 2
    @RomanY thanks for comment, but I never found "all not equal" simpler than "not any", so I find no simplification here :) Aug 31, 2015 at 5:35
  • The specified LINQ expression contains references to queries that are associated with different contexts.
    – Henjin
    Mar 24, 2020 at 6:45
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.