【发布时间】:2011-12-05 17:52:31
【问题描述】:
我只是偶然发现了这段代码,我想知道为什么 Count 在循环期间完成。
/// <summary>
/// find the first index in a sequence to satisfy a condition
/// </summary>
/// <typeparam name="T">type of elements in source</typeparam>
/// <param name="source">sequence of items</param>
/// <param name="predicate">condition of item to find</param>
/// <returns>the first index found, or -1 if not found</returns>
public static int FindIndex<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
for (int i = 0; i < source.Count(); i++)
{
if (predicate(source.ElementAt(i))) return i;
}
return -1; // Not found
}
如果计数可以改变,我们不应该这样做吗:for (int i = source.Count() - 1; i >= 0; i--)
否则,我认为我们应该在循环开始之前计算计数,而不是每次。
这样做的正确方法是什么?
【问题讨论】:
标签: c# linq ienumerable