c# List.Contains() Method Returns False

后端 未结 9 1865
梦毁少年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
    闹比i (楼主)
    2021-01-28 06:39

    You need to implement the IEqualityComparer

    More information on how to do it can be found here; http://msdn.microsoft.com/en-us/library/bb339118.aspx

    // Custom comparer for the class 
     class CarComparer : IEqualityComparer
    {
    // Products are equal if their names and product numbers are equal. 
    public bool Equals(Car x, Car y)
    {
    
        //Check whether the compared objects reference the same data. 
        if (Object.ReferenceEquals(x, y)) return true;
    
        //Check whether any of the compared objects is null. 
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;
    
        //Check whether the properties are equal. 
        return x.CarID == y.CarID && x.CarName == y.CarName;
    }
    
    // If Equals() returns true for a pair of objects  
    // then GetHashCode() must return the same value for these objects. 
    
    public int GetHashCode(Car car)
    {
        //Check whether the object is null 
        if (Object.ReferenceEquals(car, null)) return 0;
    
        //Get hash code for the Name field if it is not null. 
        string hashCarName = car.CarName == null ? 0 : car.CarName.GetHashCode();
    
        //Get hash code for the ID field. 
        int hashCarID = car.CarID.GetHashCode();
    
        //Calculate the hash code for the product. 
        return hashCarName ^ hashCarID;
    }
    

    Check for equality;

    CarComparer carComp = new CarComparer();
    bool blnIsEqual = CarList1.Contains(CarList2, carComp);
    

提交回复
热议问题