Nilesh Barai
Nilesh Barai

Reputation: 1322

Searching data in a list using linq

I have an int List of lotItemIds (lotItemIdList). From BookingItems I want to select only such BookingItems whose BookingItemId is not present in the lotItemIds List.

I wrote an expression as below:

 var Booking = context.Bookings.Include(x => x.BookingItems.Select(y => y.LotItem))
                               .FirstOrDefault(x => x.BookingId == BookingId 
                                && x.BookingItems.Any(y => !lotItemIdList.Contains(y.BookingItemId)));

But this is selecting all the items even if those are present in the lotItemIdList.

Upvotes: 0

Views: 57

Answers (2)

Tim
Tim

Reputation: 15247

OK, so you want the Booking itself, then you're on the right track, though you seem to be doing stuff that isn't necessary based on your description. This should work:

var bookings = context.Bookings
                      .Where(b => b.BookingItems
                                   .Any(bi => !lotItemIdList.Contains(bi => bi.BookingItemId)));

You're getting all Bookings where any one of the Bookings' BookingItems has an Id that is not in the list.

Upvotes: 1

Andre Pena
Andre Pena

Reputation: 59416

From your description, this is what you want:

var bookingItems = context.Bookings.Where(b => !lotItemIdList.Contains(b.BookingItemId));

Upvotes: 0

Related Questions