如何在 Collection 继承类中找到元素的索引?
public class MyCollection : Collection<MyClass>
{
// implementation here
}
我尝试在集合上使用 .FindIndex 但没有成功:
int index = collectionInstance.FindIndex(someLambdaExpression);
还有其他方法可以实现这一目标吗?
如何在 Collection 继承类中找到元素的索引?
public class MyCollection : Collection<MyClass>
{
// implementation here
}
我尝试在集合上使用 .FindIndex 但没有成功:
int index = collectionInstance.FindIndex(someLambdaExpression);
还有其他方法可以实现这一目标吗?
如果您直接拥有该元素,则可以使用IndexOf来检索它。但是,这不适用于通过 lambda 查找元素索引。
但是,您可以使用 LINQ:
var index = collectionInstance.Select( (item, index) => new {Item = item, Index = index}).First(i => i.Item == SomeCondition()).Index;
如果可能(对不起,如果不是,并且您受到先前选择的限制),并且如果您的用例能够使用索引,那么您最好使用通用列表(即:列表)。
然后你就可以正确使用 FindIndex 了。
public class MyList : List<MyClass>
{
// implementation here
}
...
int index = listInstance.FindIndex(x => x.MyProperty == "ThePropertyValueYouWantToMatch");
Collection<T>.IndexOf
调用不足有什么原因吗?