LINQ – "Where" Extension Method

Here is simple LINQ example where I have used Extension methods “Where”, to select the participants whose score is greater than 80.

var participants =
.Where(participant=> participant.Score > 80)
.OrderByDescending(participant => parricipant.Score)
.Select(participant => new { participant.Id,
Name=participant.Name });

Note: here we are sending a Lamda expression (participant=>participant.Score>80) as parameter of the “Where” extension method. Ever wondered how this extension method is declared and what is happening inside?

Here you go:

public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, Boolean> predicate)
  foreach (TSource element in source)
    if (predicate(element))
    yield return element;

I am sure you noticed the “this” word in the above code snippet, that’s  how extension methods are declared, simply adding a “this” word turns your method into an Extension Method.