Delete items from a list that are in another list by a specific property?

advertisements

I have two lists:

ListA with CancelledFlights
ListB with all Flights

I would like to remove all CancelledFlights from ListB with all flights compared not by the object but by the property FlightNumber. How could I achieve this with Lambda or LINQ? I know how to select in LINQ and lambda but not how to remove ...


You can use linq to do that

var cancelledFlightNumbers = ListA
    .Select(x => x.FlightNumber)
    .ToList();

var cancelledFlightsRemoved = ListB
    .Where(x => !cancelledFlightNumbers.Contains(x.FlightNumber))
    .ToList();

If you have too many items then you can use HashSet to improve performance

var cancelledFlightNumbers = new HashSet<int>(ListA.Select(x => x.FlightNumber));