c# List.Contains() Method Returns False

后端 未结 9 1962
梦毁少年i
梦毁少年i 2021-01-28 06:04

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

9条回答
  •  温柔的废话
    2021-01-28 06:41

    A collection can never "contain" a newly newed 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:

    1. Override Car.Equals (and Car.GetHashCode) to specify what it means to be equivalent, or

    2. 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]))
    

提交回复
热议问题