在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; } }更多推荐
给定项目的属性,获取列表中项目的索引
发布评论