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

25.1k Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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;
0
On

Is there a reason why calling Collection<T>.IndexOf is insufficient?

2
On

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 (i.e.: 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");