Determine objects to delete from a database I have the following method which determines which cars I need to delete from the DB.

private List&lt;CarDTO&gt; BuildCarsToDelete(IList&lt;CarDTO&gt; newCars, IList&lt;CarDTO&gt; existingCars)
{
    var missingCars = new List&lt;CarDTO&gt;();

    var cars = newCars.Select(c =&gt; c.CarId);
    var newCarIds = new HashSet&lt;int&gt;(cars);

    foreach (var car in existingCars)
    {
        //If there are no new cars then it had some and they have been removed
        if (newCars.Count() == 0)
        {
            missingCars.Add(car);
        }
        else
        {
            if (!newCarIds.Contains(car.CarId))
            {
                missingCars.Add(car);
            }
        }
    }

    return missingCars;
}


This works as expecting - but if I want to achieve the same functionality for Customers or Apartments of other DTOs I will be copying a pasting the code but only changing the variable names and the Type of DTO around - is there a nicer way possible using generics which would keep the algorithm and logic as it is but allow me to use on any DTO?
There is an easier way to find the cars to delete. You just need to use the Except extension.

var carsToDelete = existingCars.Except(newCars);


In order for this to work you have two choices:


you can either implement the IEquatable for each DTO or
you can implement a common interface for the Id and a custom IEqualityComparer&lt;IYourInterface&gt; and use it with the Except extension.