Bob Tway
Bob Tway

Reputation: 9603

Linq - get objects with a list property that does not contain values in another list

I feel like a complete idiot not being able to work this out myself.

I have a list of "Booking" objects called ExistingBookings. I also have an ObservableCollection of "Count" objects each of which has a "Bookings" property which is a list of "Booking" objects.

Using Linq, how do I select all the Count objects whose "Bookings" property does not contain any of the "Booking" objects in ExistingBookings?

i.e.

List<Booking> ExistingBookings = new List<Booking>();
ExistingBookings.Add(Booking1);
ExistingBookings.Add(Booking2);

Count1 = new Count();
Count1.Bookings.Add(Booking2);
Count1.Bookings.Add(Booking3);

Count2 = new Count();
Count1.Bookings.Add(Booking3);
Count1.Bookings.Add(Booking4);

List<Count> counts = new List<Count>();
counts.Add(Count1);
counts.Add(Count2);

I am expecting the output to be a list of Count objects containing only Count2, since neither of its Booking objects exist in ExistingBookings.

Please put me out of my misery :(

Upvotes: 0

Views: 2394

Answers (2)

Lee
Lee

Reputation: 144126

Assuming your Booking class implements equality and hash codes correctly you can use:

var result = counts.Where(c => !c.Bookings.Intersect(ExistingBookings).Any());

Upvotes: 2

Andrei
Andrei

Reputation: 56688

counts.Where(c => c.Bookings.All(b => !ExistingBookings.Contains(b)));

Upvotes: 1

Related Questions