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

标签 c# list class contains

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

这是列表:

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

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

if (CartProducts.Contains(p))

它会忽略类似的购物车产品,而且我似乎不知道它检查的是什么 - ID?还是根本没有?

最佳答案

如果您使用的是 .NET 3.5 或更新版本,您可以使用 LINQ 扩展方法来实现“包含”检查 Any扩展方法:

if(CartProducts.Any(prod => prod.ID == p.ID))

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

这也有利于 LINQ-to-SQL 查询以及内存中查询,而 Contains 没有。

关于c# - .Contains() 在自定义类对象列表上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2629124/

相关文章:

c# - 将 XSLT 文件包含到可执行文件中

c# - 您将如何在单个 ASP.Net MVC Web 应用程序中构建访问者和管理功能?

c# - 在结构中,通过 Equals 实现 operator== 是否有效,但不覆盖 Equals 和 GetHashCode?

python - 在 Python 中追加字典

javascript - Node.js多次实例化类

c# - 使用 Entity Framework 代码优先创建表、运行时

java - Android Sugar ORM - 带列表的类模型

Python - 连接 2 个列表

c++ - 无论选择什么选项,函数 "void sub(int Subtraction)"都保持打印

c++ - 在 main 中访问类数据