.Contains()在自定义类对象列表上

Jan*_*sen 83 c# class contains list

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

这是清单:

List<CartProduct> CartProducts = new List<CartProduct>();
Run Code Online (Sandbox Code Playgroud)

而且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;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我试着在列表中找到类似的cartproduct:

if (CartProducts.Contains(p))
Run Code Online (Sandbox Code Playgroud)

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

提前致谢!:)

Pau*_*ner 127

如果您使用的是.NET 3.5或更高版本,则可以使用LINQ扩展方法通过扩展方法实现"包含"检查Any:

if(CartProducts.Any(prod => prod.ID == p.ID))
Run Code Online (Sandbox Code Playgroud)

这将检查是否存在CartProducts具有与ID匹配的ID的产品p.您可以在=>执行检查后放置任何布尔表达式.

这也有利于LINQ-to-SQL查询以及内存查询,而Contains不是.


Row*_*haw 105

您需要实现IEquatable或覆盖Equals()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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 但是``GetHashCode()''在哪里? (2认同)
  • 您不需要实现 GetHashCode()。没有它它也能工作。 (2认同)

Mar*_*lan 10

它检查列表中是否包含特定对象.

您最好使用列表中的Find方法.

这是一个例子

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

CartProduct objBeer;
objBeer = lst.Find(x => (x.Name == "Beer"));
Run Code Online (Sandbox Code Playgroud)

希望有所帮助

你也应该看看LinQ - 这可能是一种过度杀伤,但仍然是一个有用的工具......


Ric*_*ard 5

默认情况下,引用类型具有引用相等性(即两个实例仅当它们是同一对象时才相等)。

您需要覆盖Object.Equals(并Object.GetHashCode匹配)以实现您自己的平等。(然后,实现等号、==、 运算符是一个很好的做法。)