簡體   English   中英

如何在Collection中找到元素索引 <T> 繼承了什么?

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

如何在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;

是否有理由調用Collection<T>.IndexOf不足?

如果可能(抱歉,如果不是,並且您受到先前選擇的約束),並且如果您的用例是能夠使用索引,那么最好使用通用列表(即:List)。

然后你就可以正確使用FindIndex了。

public class MyList : List<MyClass>
{
    // implementation here
}

...

int index = listInstance.FindIndex(x => x.MyProperty == "ThePropertyValueYouWantToMatch");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM