c# List.Contains() Method Returns False

后端 未结 9 1868
梦毁少年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条回答
  •  -上瘾入骨i
    2021-01-28 06:53

    You are assuming that two Car instances that have the same CarID and CarName are equal.

    This is incorrect. By default, each new Car(...) is different from each other car, since they are references to different objects.

    There are a few ways to "fix" that:

    • Use a struct instead of a class for your Car.

      Structs inherit ValueType's default implementation of Equals, which compares all fields and properties to determine equality.

      Note that in this case, it is recommended that you make your Car struct immutable to avoid common problems with mutable structs.

    • Override Equals and GetHashCode.

      That way, List.Contains will know that you intend Cars with the same ID and Name to be equal.

    • Use another method instead of List.Contains.

      For example, Enumerable.Any allows you to specify a predicate that can be matched:

      bool exists = myCars.Any(car => car.ID == Convert.ToInt64(strCar.Split(':')[1])
                                      && car.Name = strCar.Split(':')[2]);
      

提交回复
热议问题