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

TheBoyan picture TheBoyan · Mar 3, 2011 · Viewed 21.1k times · Source

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?

Answer

Reed Copsey picture Reed Copsey · Mar 3, 2011

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;