其中一种方法
- List<T>.IndexOf()和
- List<T>.FindIndex()
- List<T>.IndexOf() and
- List<T>.FindIndex()
在处理时间方面更有效吗?
is more efficient in terms of processing time?
在这种情况下,T的类型为String.
The type of T in this instance is String.
推荐答案IndexOf使用要搜索的对象的Equals实现来执行for循环. FindIndex也会执行for循环,但会评估Predicate来检查是否匹配.
IndexOf performs a for-loop, using the Equals implementation of the objects being searched to look for a match. FindIndex also peforms a for-loop but evaluates a Predicate to check for a match instead.
他们每个人都归结为一个循环.性能上的差异(如果有的话)可以忽略不计.以下是一些MSDN摘录:
They each boil down to a for-loop. The difference in performance, if any, will be negligible. Here are some MSDN excerpts:
List<T>.IndexOf Method (T) :
此方法执行线性搜索;因此,此方法是O( n )操作,其中 n 是Count.
This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.
List<T>.FindIndex Method (Predicate<T>) :
此方法执行线性搜索;因此,此方法是O( n )操作,其中 n 是Count.
This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.
也就是说,这两个函数的用法有很大不同.前者假定您有一个来自列表的对象,而您只需要知道该对象在列表中的索引位置(如果有).
That said, the two functions would be used quite differently. The former assumes you have an object from the list, and you just need to know at what index it exists at (if any) in the list.
后者假设您了解某个对象的某些条件,并且您想找到列表中对象与该条件匹配的第一个索引.可能有多个匹配项,但是该方法返回第一个匹配项.
The latter assumes you know some criteria about an object, and you want to find the first index where an object in the list matches that criteria. There could be multiple matches, but the method returns the first match.
更多推荐
List T.IndexOf()与List T.FindIndex()的效率
发布评论