6

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?

TheBoyan
  • 6,802
  • 3
  • 45
  • 61

3 Answers3

9

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;
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

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");
davidsbro
  • 2,761
  • 4
  • 23
  • 33
yorah
  • 2,653
  • 14
  • 24
  • Unfortunately, the nature of things is that I cannot make such a decision at this time....I wish we lived in a perfect world, hahahah – TheBoyan Mar 03 '11 at 18:39
  • Relevant to this answer: https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt – user654123 Jan 20 '18 at 13:10
1

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

mqp
  • 70,359
  • 14
  • 95
  • 123