[英]Checking if a list of objects contains a property
嗨,我有一个对象列表,我需要找出我所拥有的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; }
public int Id { get; set; }
public int Id { get; set; }
。 另外,将所有引用从id
更改为Id
。
将using System.Linq
添加到您的业务逻辑文件。
将if (Inv.Contains(id))
更改为if (Inv.Any(x => x.Id == id))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.