0

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. :)

KidBilly
  • 3,408
  • 1
  • 26
  • 40
  • I think that answers my question. So if I understand correctly, the answer from that post is to not remove from the a list but build a new list based on the property to match. Is that right? – KidBilly Mar 22 '21 at 22:31
  • Yes, that is the LINQ way. Do you need to actually remove the items from an existing list instance? Or is the solution to the duplicate link good enough? – Lasse V. Karlsen Mar 22 '21 at 22:44
  • If you absolutely must adjust an existing list instance, you can use something like this: `int index = 0; HashSet seenCarIds = new HashSet(); while (index < cars.Count) { if (seenCarIds.Add(cars[index].ID)) index++; else cars.RemoveAt(index); }` – Lasse V. Karlsen Mar 22 '21 at 22:46
  • If you're going through a billion items, there may be other more efficient way, and you have to balance time & space efficiencies. But for short, easy-to-follow LINQ solutions, a `GroupBy().ToList()` is the way to go – NPras Mar 22 '21 at 22:49
  • MoreLINQ has a `DistinctBy()` method that would work. `cars.DistinctBy(x => x.ID)` – user2051770 Mar 23 '21 at 14:59

1 Answers1

0

I think this is what you want, it will filter your cars by ID.

cars = cars.GroupBy(c => c.Id).Select(c => c.First()).ToList();

yzAlvin
  • 36
  • 2