如何在不循环的情况下找到列表中项目的索引?
目前这看起来不太好 - 在列表中搜索相同的项目两次,只是为了得到索引:
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。
对于简单类型,您可以使用“IndexOf”:
List<string> arr = new List<string>();
arr.Add("aaa");
arr.Add("bbb");
arr.Add("ccc");
int i = arr.IndexOf("bbb"); // RETURNS 1.
编辑:如果你只使用List<>
而你只需要索引,那么List.FindIndex
确实是最好的方法。我会把这个答案留给那些需要任何不同的人(例如在任何IEnumerable<>
之上)。
使用Select
的重载,它在谓词中获取一个索引,因此您将列表转换为(索引,值)对:
var pair = myList.Select((Value, Index) => new { Value, Index })
.Single(p => p.Value.Prop == oProp);
然后:
Console.WriteLine("Index:{0}; Value: {1}", pair.Index, pair.Value);
或者如果你只想要索引并且你在多个地方使用它,你可以轻松编写自己的扩展方法,就像Where
,但它不返回原始项,而是返回与谓词匹配的那些项的索引。
如果您不想使用LINQ,那么:
int index;
for (int i = 0; i < myList.Count; i++)
{
if (myList[i].Prop == oProp)
{
index = i;
break;
}
}
这样你只迭代一次列表。
这是List Of String的代码:
int indexOfValue = myList.FindIndex(a => a.Contains("insert value from list"));
这是整数列表的代码:
int indexOfNumber = myList.IndexOf(/*insert number from list*/);
这是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;
}
}
请享用。
找到List中任何字符串值的索引的简单解决方案。这是List Of String的代码:
int indexOfValue = myList.FindIndex(a => a.Contains("//insert value from list"));
查找List中任何Integer值的索引的简单解决方案。这是整数列表的代码:
int indexOfNumber = myList.IndexOf(//insert number from list);