我如何获得自定义类中的对象的索引?
问题描述:
我想要一个表示对象列表的类的indexof方法。我想知道最好的方法。下面是我提出的代码。我如何获得自定义类中的对象的索引?
public int IndexOf(Product product)
{
Product p;
for (int i = 0; i < products.Count; i++)
{
p = products[i];
if (p == product)
return i;
}
return -1;
}
答
如果产品类型是List<Product>
你可以用你收集的IndexOf()
方法:
public int IndexOf(Product product)
{
return products.IndexOf(product);
}
+0
你打我20秒,我不得不检查IList
+0
我不得不检查;-) – BrokenGlass 2012-02-04 21:16:53
是'products'一个'名单'? “产品”的类型是什么? –
rcdmk
2012-02-04 21:13:44
是的,它的类型产品列表 – Xerxes 2012-02-04 21:15:41
我正在写答案,但似乎有人给你第一个。 – rcdmk 2012-02-04 21:16:51