检查对象列表是否包含属性

本文关键字:包含 属性 是否 列表 对象 检查 | 更新日期: 2024-10-22 03:46:14

嗨,我有一个对象列表,我需要知道我的id是否已经在列表中。在对象类中,我已经设置了id,我只想知道在Ui中输入的id是否已经在使用中。

class Product
{
    private string name = "";
    private int id = 0;
    private decimal Pvalue = 0.00m;
    private static int lastId = 1;
    public Product(string namep, decimal valuep)
    {
        this.name = namep;
        this.id = lastId++;
        this.Pvalue = valuep;
    }

    public override string ToString()
    {
        return name + "     " + id + "    "+ Pvalue;
    }

    public bool Equals(Product p)
    {
        return (p.id == this.id);
    }
}

我正在努力解决这个问题:

 int id;
        bool test = int.TryParse(textBoxId.Text, out id);

            if(test)
            {

                if(Inv.Contains(id))
                {
                label2.Text = "you already have this id";
                }else
                {
                    label2.Text = "you can use this id";            
                }
            }

如果有人知道为什么这不起作用,或者有更好的方法可以拯救我的背部,谢谢。

检查对象列表是否包含属性

private int id = 0;更改为public int Id { get; set; }。此外,将所有引用从id更改为Id

using System.Linq添加到业务逻辑文件中。

if (Inv.Contains(id))更改为if (Inv.Any(x => x.Id == id))

相关文章: