开发者

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

开发者 https://www.devze.com 2023-02-14 11:40 出处:网络
How do you find the index of an element in a Collection inherited class? public class MyCollection : Collection<MyClass>

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.FindInde开发者_如何学Cx(someLambdaExpression);

Any other ways to achieve this?


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;


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");


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号