How do you find an element index in a Collection<T> inherited class?

How do you find the index of an element in a Collection inherited class?

public class MyCollection : Collection<MyClass>
{
   // implementation here
}

I tried to use .FindIndex on the collection but no success:

 int index = collectionInstance.FindIndex(someLambdaExpression);

Any other ways to achieve this?


If you have the element directly, you can use IndexOf to retrieve it. However, this won't work for finding an element index via a lambda.

You could use LINQ, however:

var index = collectionInstance.Select( (item, index) => new {Item = item, Index = index}).First(i => i.Item == SomeCondition()).Index;

为什么调用Collection<T>.IndexOf不够?


If possible (sorry if it's not, and you're constrained by previous choices), and if your use case is to be able to work with indexes, you would be better off using generic lists (ie: List).

Then you would be able to use FindIndex correctly.

public class MyList : List<MyClass>
{
    // implementation here
}

...

int index = listInstance.FindIndex(x => x.MyProperty == "ThePropertyValueYouWantToMatch");
链接地址: http://www.djcxy.com/p/53934.html

上一篇: 成语的容器类

下一篇: 如何在Collection <T>继承类中找到元素索引?