Этот ответ немного более технический ... Помните, что лямбды - это просто синтетические ярлыки для анонимных делегатов (которые являются анонимными методами). Редактировать: Они также могут быть деревьями выражений в зависимости от подписи Where
(см. Комментарий Марка).
list.Where((item, index) => index < list.Count - 1 && list[index + 1] == item)
функционально эквивалентно
// inline, no lambdas
list.Where(delegate(item, index) { return index < list.Count - 1 && list[index + 1] == item; });
// if we assign the lambda (delegate) to a local variable:
var lambdaDelegate = (item, index) => index < list.Count - 1 && list[index + 1] == item;
list.Where(lambdaDelegate);
// without using lambdas as a shortcut:
var anonymousDelegate = delegate(item, index)
{
return index < list.Count - 1 && list[index + 1] == item;
}
list.Where(anonymousDelegate);
// and if we don't use anonymous methods (which is what lambdas represent):
function bool MyDelegate<TSource>(TSource item, int index)
{
return index < list.Count - 1 && list[index + 1] == item;
}
list.Where(MyDelegate);
Метод Where
имеет следующую подпись:
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
, что эквивалентно:
delegate bool WhereDelegate<TSource>(TSource source, int index);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, WhereDelegate<TSource> predicate);
Здесь определены элемент и индекс.
ПозадиWhere
может сделать что-то вроде (просто предположение, вы можете декомпилировать, чтобы увидеть):
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
{
int index = 0;
foreach (TSource item in source)
{
if (predicate(index, source))
yield return item;
index++;
}
}
Так вот, где индекс инициализируется и передается вашему делегату (анонимному, лямбда или как-то иначе).