Search code examples
c#listclasscontains

.Contains() on a list of custom class objects


I'm trying to use the .Contains() function on a list of custom objects.

This is the list:

List<CartProduct> CartProducts = new List<CartProduct>();

And the CartProduct:

public class CartProduct
{
    public Int32 ID;
    public String Name;
    public Int32 Number;
    public Decimal CurrentPrice;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="ID">The ID of the product</param>
    /// <param name="Name">The name of the product</param>
    /// <param name="Number">The total number of that product</param>
    /// <param name="CurrentPrice">The currentprice for the product (1 piece)</param>
    public CartProduct(Int32 ID, String Name, Int32 Number, Decimal CurrentPrice)
    {
        this.ID = ID;
        this.Name = Name;
        this.Number = Number;
        this.CurrentPrice = CurrentPrice;
    }
    public String ToString()
    {
        return Name;
    }
}

When I try to find a similar cartproduct within the list:

if (CartProducts.Contains(p))

it ignores similar cartproducts and I don't seem to know what it checks on - the ID? or at all?


Solution

  • You need to implement IEquatable or override Equals() and GetHashCode()

    For example:

    public class CartProduct : IEquatable<CartProduct>
    {
        public Int32 ID;
        public String Name;
        public Int32 Number;
        public Decimal CurrentPrice;
    
        public CartProduct(Int32 ID, String Name, Int32 Number, Decimal CurrentPrice)
        {
            this.ID = ID;
            this.Name = Name;
            this.Number = Number;
            this.CurrentPrice = CurrentPrice;
        }
    
        public String ToString()
        {
            return Name;
        }
    
        public bool Equals( CartProduct other )
        {
            // Would still want to check for null etc. first.
            return this.ID == other.ID && 
                   this.Name == other.Name && 
                   this.Number == other.Number && 
                   this.CurrentPrice == other.CurrentPrice;
        }
    }