如何通过一个步骤获取列表中项目的索引? [英] How can I get the index of an item in a list in a single step?
本文介绍了如何通过一个步骤获取列表中项目的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不循环的情况下找到列表中项目的索引?
目前这看起来不太好 - 在列表中搜索相同的项目两次,只是为了获取索引:
var oProp = something;int theThingIActuallyAmInterestedIn = myList.IndexOf(myList.Single(i => i.Prop == oProp));
解决方案
int index = myList.FindIndex(a => a.Prop == oProp);
<块引用>
此方法执行线性搜索;因此,这种方法是一种O(n) 操作,其中 n 是 Count.
如果没有找到,返回-1
How can I find the index of an item in a list without looping through it?
Currently this doesn't look very nice - searching through the list for the same item twice, just to get the index:
var oProp = something;
int theThingIActuallyAmInterestedIn = myList.IndexOf(myList.Single(i => i.Prop == oProp));
解决方案
How about the List.FindIndex Method:
int index = myList.FindIndex(a => a.Prop == oProp);
This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.
If the item is not found, it will return -1
这篇关于如何通过一个步骤获取列表中项目的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文