我如何获得自定义类中的对象的索引?

问题描述:

我想要一个表示对象列表的类的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; 
    } 
+1

是'products'一个'名单'? “产品”的类型是什么? – rcdmk 2012-02-04 21:13:44

+0

是的,它的类型产品列表 – Xerxes 2012-02-04 21:15:41

+0

我正在写答案,但似乎有人给你第一个。 – rcdmk 2012-02-04 21:16:51

如果产品类型是List<Product>你可以用你收集的IndexOf()方法:

public int IndexOf(Product product) 
{ 
    return products.IndexOf(product); 
} 
+0

你打我20秒,我不得不检查IList 实际上是否有这种方法;) – 2012-02-04 21:15:50

+0

我不得不检查;-) – BrokenGlass 2012-02-04 21:16:53

我不能让.IndexOf()我的问题的工作,但我发现下面解决方案工作。

How to use IndexOf() method of List<object>