您可以使用Where 重载,它将Func<TSource, int, bool> predicate 作为输入。此委托的第二个输入是当前元素的索引。因此,这意味着您的 lambda 表达式必须接受两个输入,第一个是元素的类型,另一个是 Int32。
Where 方法会自动计算当前元素的索引。
var result = myColl.Where((x, index) => index >= 3 && x.Count > myColl.ElementAt(index - 3).Count);
然后您可以使用您想要的方法,如Select()、ToList() 等。
PS:我假设对象的名称是myColl。
另外:
我总是喜欢告诉开发者http://referencesource.microsoft.com/。您可以轻松找到所有方法的实现以及有关 C# 源代码的所有内容。
如果您有兴趣,这里是Where 方法重载的源代码。
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate) {
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
return WhereIterator<TSource>(source, predicate);
}
如您所见,它将返回WhereIterator,它会自动计算当前项目的索引并将其发送到您的方法:
static IEnumerable<TSource> WhereIterator<TSource>(IEnumerable<TSource> source, Func<TSource, int, bool> predicate) {
int index = -1;
foreach (TSource element in source) {
checked { index++; }
if (predicate(element, index)) yield return element;
}
}