I am fairly new to LINQ. I am looking at this code, and not sure if I understand this properly. I realize that it is an extension and generic method, but what is predicate(item, index) performing (lets say i pass in an array of ints when calling this method)?
I know that predicate is a delegate, but maybe I just don’t know how delegation works, someone has any good example/explanation they’d like to give. Also, what is yield keyword, is it just used in linq stuff?
private static IEnumerable<TSource> WhereImpl<TSource>(
this IEnumerable<TSource> source,
Func<TSource, int, bool> predicate)
{
int index = 0;
foreach (TSource item in source)
{
if (predicate(item, index))
{
yield return item;
}
index++;
}
}
I am trying to follow Reimplementing LINQ to Objects: Part 2 – “Where” from Skeet’s blog.
is defined to be of type
that means a method that has parameters of
TSourceandintand returns abool– a predicate.An example for
TSource=stringcould be (totally made up):yieldis specific to iterator blocks – this has been around before LINQ. It basically works like a state machine –yield return item;will return item to the caller and suspend execution, but once you request the next item, execution will resume on the next line. It’s easiest to see how it works if you step through it with a debugger.