简体   繁体   中英

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?

ie

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 :(

假设您的Booking类正确实现了相等和哈希码,则可以使用:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM