Search code examples
c#inheritancegeneric-collections

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?


Solution

  • 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;