How can I remove objects from a List<Object>
based on a duplicate ID? For example:
public class Car
{
public int ID { get; set; }
public string Color { get; set; }
public string Year { get; set }
}
Car car1 = new Car()
{
ID = 123,
Color = "green",
Year = "2010"
};
Car car2 = new Car()
{
ID = 123,
Color = "blue",
Year = "2012"
};
Car car3 = new Car()
{
ID = 153,
Color = "black",
Year = "2020"
};
var cars = new List<Car>();
cars.Add(car1);
cars.Add(car2);
cars.Add(car3);
If there's duplicate IDs, I need to remove all but the first one. In the above example, I would need to remove only car2
. Maybe there's a good LINQ
way to do this?
The recommended SO post does answer my question since it's not necessary for me to modify an existing list. Creating a new list with my requirements as described in the post is sufficient. :)