开发者

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.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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜