Search code examples
c#linqextension-methods

How do I correlate a Linq query extension method to its signature in the documentation?


Take this code from MSDN:

The following code example demonstrates how to use Where(IEnumerable, Func) to filter a sequence.

List<string> fruits =
    new List<string> { "apple", "passionfruit", "banana", "mango", 
                    "orange", "blueberry", "grape", "strawberry" };

IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 6);

foreach (string fruit in query)
{
    Console.WriteLine(fruit);
}
/*
 This code produces the following output:

 apple
 mango
 grape
*/

When I look at the signature,

Where<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)

Which part of (fruit => fruit.length < 6) is IEnumerable<TSource>? And does Func<TSource, Boolean> include the entire lambda or just what comes after the =>? I am guessing that behind the scenes Where's <TSource> is replaced by the compiler with the correct type for the Generic, but I don't know how to read the rest.

EDIT: Would it be easier to understand if this were a delegate instead of a lambda, as far as seeing what points to what in the documentation?


Solution

  • If you look at the method signature you see it defined as

    public static Enumerable
    {
        public static IEnumerable<TSource> Where<TSource>(
            this IEnumerable<TSource> source,
            Func<TSource, bool> predicate
        )
    }
    

    the this makes it a extension method. so doing

    fruits.Where(fruit => fruit.Length < 6);
    

    is the exact same thing as doing

    Enumerable.Where(fruits, fruit => fruit.Length < 6);
    

    So to answer your question the IEnumerable<T> is to the left of the .