Compare two object lists with LINQ on specific property

10,839

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);
Share:
10,839
Niklas
Author by

Niklas

System Developer / Consultant http://www.linkedin.com/pub/niklas-kihl/47/891/856

Updated on June 04, 2022

Comments

  • Niklas
    Niklas almost 2 years

    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);
    
  • Niklas
    Niklas almost 10 years
    Thank you, I prefer the compact version though.
  • Jon Skeet
    Jon Skeet almost 10 years
    @Niklas: You mean the first one? That's fine - the second was really just trying to unpack that in case you had problems understanding it.