I have a structure (struct) with 2 fiels ID and Name. Then I created a List of this structure but anytime I do a contains it works for the first time adding it to the collection but then it's not working anymore. Why? It's not a reference is a struct. I want to validate if this isn't in the list add it.
public struct MyCar
{
public int id { get; set; }
public string name { get; set; }
}
List<MyCar> cars = new List<MyCar>();
MyCar myCar = new MyCar();
myCar.id = 1;
myCar.name = "a";
if(cars.Contains(myCar) == false)
{
cars.Add(myCar);
}
myCar = new MyCar();
myCar.id = 2;
myCar.name = "b";
if(cars.Contains(myCar) == false)
{
cars.Add(myCar);
}
myCar = new MyCar(); //Wrong. Duplicate and it's gonna be added again because Contains == false
myCar.id = 1;
myCar.name = "a";
if(cars.Contains(myCar) == false)
{
cars.Add(myCar);
}
Maybe I can use the Find to match for => X.ID and => X.NAME but I don't want this because my struct in fact is more complex that this two fields.