In the code block below I would expect dictCars to contain: { Chevy:Camaro, Dodge:Charger }
But, dictCars comes back empty. Because this line returns false each time it
A collection can never "contain" a newly new
ed object which uses the default Object.Equals
comparison. (The default comparison is ReferenceEquals
, which simply compares instances. This will never be true comparing an existing Car
with a new Car()
)
To use Contains
in this way, you will need to either:
Override Car.Equals
(and Car.GetHashCode
) to specify what it means to be equivalent, or
Implement an IEqualityComparer
to compare the instances and specify that in your call to Contains
.
Note the side effect that in the first option, other uses of Car.Equals(Car)
will also use this comparison.
Otherwise, you can use Any
and specify the comparison yourself (but IMHO this smells a little funny - a Car should know how to compare itself):
if(myCars.Any(c=> c.CarID == Convert.ToInt64(strCar.Split(':')[1]) && c.CarName == strCar.Split(':')[2]))