.Contains() on a list of custom class objects

前端 未结 7 2205
天命终不由人
天命终不由人 2020-11-27 02:38

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

This is the list:

List CartProducts = new Lis         


        
7条回答
  •  悲哀的现实
    2020-11-27 03:20

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

    For example:

    public class CartProduct : IEquatable
    {
        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;
        }
    }
    

提交回复
热议问题