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);
Author by
Niklas
System Developer / Consultant http://www.linkedin.com/pub/niklas-kihl/47/891/856
Updated on June 04, 2022Comments
-
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 inavailableBookings
. The LINQ join below will only get me the bookingids that are inavailableBookings
, 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 almost 10 yearsThank you, I prefer the compact version though.
-
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.