给定项目的属性,获取列表中项目的索引 [英] Get the index of item in a list given its property
问题描述
在MyList
List<Person>
中,可能存在Person
,其Name
属性设置为"ComTruise".我需要在MyList
中首次出现"ComTruise"的索引,而不是整个Person
元素.
In MyList
List<Person>
there may be a Person
with its Name
property set to "ComTruise". I need the index of first occurrence of "ComTruise" in MyList
, but not the entire Person
element.
我现在正在做的是:
string myName = ComTruise;
int thatIndex = MyList.SkipWhile(p => p.Name != myName).Count();
如果列表很大,是否有更优化的方法来获取索引?
If the list is very large, is there a more optimal way to get the index?
推荐答案
由于它是ObservableCollection
,因此您可以尝试
As it's an ObservableCollection
, you can try this
int index = MyList.IndexOf(MyList.Where(p => p.Name == "ComTruise").FirstOrDefault());
如果您的收藏夹中不存在"ComTruise",它将返回-1
.
It will return -1
if "ComTruise" doesn't exist in your collection.
如评论中所述,这将执行两次搜索.您可以使用for循环对其进行优化.
As mentioned in the comments, this performs two searches. You can optimize it with a for loop.
int index = -1;
for(int i = 0; i < MyList.Count; i++)
{
//case insensitive search
if(String.Equals(MyList[i].Name, "ComTruise", StringComparison.OrdinalIgnoreCase))
{
index = i;
break;
}
}
这篇关于给定项目的属性,获取列表中项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!