.Contains() 在自定义类对象列表上 [英] .Contains() on a list of custom class objects

查看:31
本文介绍了.Contains() 在自定义类对象列表上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对自定义对象列表使用 .Contains() 函数

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

这是列表:

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

还有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;
    }
}

所以我尝试在列表中找到类似的购物车产品:

So i try to find a similar cartproduct within the list:

if (CartProducts.Contains(p))

但它忽略了类似的购物车产品,而且我似乎不知道它检查了什么 - ID?还是全部?

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

提前致谢!:)

推荐答案

你需要实现 IEquatable 或覆盖 Equals()GetHashCode()

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

例如:

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;
    }
}

这篇关于.Contains() 在自定义类对象列表上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆