Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 466
TheBoyan Avatar asked Dec 16 '22 16:12

TheBoyan


1 Answers

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;
like image 85
Reed Copsey Avatar answered Apr 26 '23 18:04

Reed Copsey