如何获得的项目的列表中的索引在单一步骤? [英] How to get the index of an item in a list in a single step?

查看:123
本文介绍了如何获得的项目的列表中的索引在单一步骤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何才能找到一个列表中的项目的索引,而不通过它循环?

目前这个看起来并不很漂亮 - 在列表中同一项目两次搜索,只是为了让指数:

  VAR oProp =东西;INT theThingIActuallyAmInterestedIn = myList.IndexOf(myList.Single(I => i.Prop == oProp));


解决方案

怎么样 List.FindIndex方法

  VAR指数= myList.FindIndex(A => a.Prop == oProp);


  

此方法执行线性搜索;因此,此方法是一种
  O(n)操作,其中n是Count。


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:

var 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.

这篇关于如何获得的项目的列表中的索引在单一步骤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆