c# List.Contains() Method Returns False

后端 未结 9 1860
梦毁少年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:50

    You need to tell Contains what makes two Cars equal. By default it will use ReferenceEquals which will only call two objects equal if they are the same instance.

    Either override Equals and GetHashCode in your Car class or define an IEqualityComparer class and pass that to Contains.

    If two Cars that have the same CarID are "equal" then the implementation is pretty straightforward:

    public override bool Equals(object o)
    {
       if(o.GetType() != typeof(Car))
         return false;
    
       return (this.CarID == ((Car)o).CarID);
    }
    
    public override int GetHashCode()
    {
      return CarID.GetHashCode();
    }
    

提交回复
热议问题