Niklas
Niklas

Reputation: 13135

Compare two object lists with LINQ on specific property

I have these two lists (where the Value in a SelectListItem is a bookingid):

List<SelectListItem> selectedbookings;
List<Booking> availableBookings;

I need to find the ids from selectedBookings that are not in availableBookings. The LINQ join below will only get me the bookingids that are in availableBookings, and I'm not sure how to do it the other way around.

!= won't work since I'm comparing strings.

results = (
  from s in selectedbookings
  join a in availableBookings on s.bookingID.ToString() equals a.Value
  select s);

Upvotes: 3

Views: 12248

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499740

I need to find the ids from selectedBookings that are not in availableBookings.

That's easy - it's all the IDs in selected bookings except those that are in available bookings:

var ids = selectedBookings.Select(x => x.bookingID.ToString())
                          .Except(availableBookings.Select(x => x.Value));

Or perhaps more readably:

var selectedIds = selectedBookings.Select(x => x.bookingID.ToString());
var availableIds = availableBookings.Select(x => x.Value);
var result = selectedIds.Except(availableIds);

Upvotes: 12

Related Questions