简体   繁体   中英

Remove items from a List which are in another List by a specific property?

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));

There are two ways I can think of to do that, one with LINQ, one simply with List<T> 's methods:

  • The List<T> approach:

    allFlights.RemoveAll(flight => cancelledFlight.Any(cancelled => cancelled.FlightNumber == flight.FlightNumber);

  • The LINQ approach:

    // an IEqualityComparer<T> that can compare objects by FlightNumber. var flightNumberComparer = new FlightNumberComparer(); allFlights = allFlights.Except(cancelledFlights, flightNumberComparer).ToList();

As you can see, for this simple scenario, RemoveAll is probably the simplest. It removes the items in-place on the original list rather than creating a new list, and will probably be easiest to write.

Remember that LINQ is a query language. It's not designed to have remove operations. At most, it can create a filtered view of a collection and create a new list based on that (like we did here). But LINQ, in itself, won't help you remove items from a list.

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