C# 如何一步获取列表中项目的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17995706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the index of an item in a list in a single step?
提问by Daniel Robinson
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));
采纳答案by Alex Filipovici
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.
此方法执行线性搜索;因此,此方法是一个 O(n) 操作,其中 n 是 Count。
If the item is not found, it will return -1
如果未找到该项目,则返回 -1
回答by Jon Skeet
EDIT: If you're onlyusing a List<>
and you onlyneed the index, then List.FindIndex
is indeed the best approach. I'll leave this answer here for those who need anything different (e.g. on top of any IEnumerable<>
).
编辑:如果您只使用 aList<>
并且您只需要索引,那么List.FindIndex
确实是最好的方法。我会把这个答案留在这里给那些需要任何不同的人(例如在 any 之上IEnumerable<>
)。
Use the overload of Select
which takes an index in the predicate, so you transform your list into an (index, value) pair:
使用Select
which 在谓词中使用索引的重载,因此您可以将列表转换为 (index, value) 对:
var pair = myList.Select((Value, Index) => new { Value, Index })
.Single(p => p.Value.Prop == oProp);
Then:
然后:
Console.WriteLine("Index:{0}; Value: {1}", pair.Index, pair.Value);
Or if you onlywant the index and you're using this in multiple places, you could easily write your own extension method which was like Where
, but instead of returning the original items, it returned the indexes of those items which matched the predicate.
或者,如果您只想要索引并且您在多个地方使用它,您可以轻松编写自己的扩展方法,就像Where
,但不是返回原始项目,而是返回与谓词匹配的项目的索引。
回答by gzaxx
If you don't want to use LINQ, then:
如果您不想使用 LINQ,则:
int index;
for (int i = 0; i < myList.Count; i++)
{
if (myList[i].Prop == oProp)
{
index = i;
break;
}
}
this way you are iterating list only once.
这样你只迭代列表一次。
回答by Jose Manuel Abarca Rodríguez
For simple types you can use "IndexOf" :
对于简单类型,您可以使用 "IndexOf" :
List<string> arr = new List<string>();
arr.Add("aaa");
arr.Add("bbb");
arr.Add("ccc");
int i = arr.IndexOf("bbb"); // RETURNS 1.
回答by Jose Manuel Abarca Rodríguez
- Simple solution to find index for any string value in the List.
- 查找列表中任何字符串值的索引的简单解决方案。
Here is code for List Of String:
这是字符串列表的代码:
int indexOfValue = myList.FindIndex(a => a.Contains("insert value from list"));
- Simple solution to find index for any Integer value in the List.
- 查找列表中任何整数值的索引的简单解决方案。
Here is Code for List Of Integer:
这是整数列表的代码:
int indexOfNumber = myList.IndexOf(/*insert number from list*/);
回答by Sn?bj?rn
Here's a copy/paste-able extension method for IEnumerable
这是 IEnumerable 的可复制/粘贴扩展方法
public static class EnumerableExtensions
{
/// <summary>
/// Searches for an element that matches the conditions defined by the specified predicate,
/// and returns the zero-based index of the first occurrence within the entire <see cref="IEnumerable{T}"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// The zero-based index of the first occurrence of an element that matches the conditions defined by <paramref name="predicate"/>, if found; otherwise it'll throw.
/// </returns>
public static int FindIndex<T>(this IEnumerable<T> list, Func<T, bool> predicate)
{
var idx = list.Select((value, index) => new {value, index}).Where(x => predicate(x.value)).Select(x => x.index).First();
return idx;
}
}
Enjoy.
享受。
回答by Ali Bordbar
If anyone wonders for the Array
version, it goes like this:
如果有人想知道这个Array
版本,它是这样的:
int i = Array.FindIndex(yourArray, x => x == itemYouWant);