Power Tools: LINQ & Lambdas
10 min · C#
Write inline functions with lambdas and transform lists with LINQ's Select and Where.
Enemy 1 of 5
Lambdas: compact inline functions
This makes a small function called square that multiplies a number by itself, then calls it with 6. Press Run to see it print 36.
Why this works
A lambda expression is a compact way to write a small, unnamed function inline, right where you need it. The syntax parameters => expression reads as "given these parameters, produce this expression's value", n => n * n means "given n, return n times n".
Assigning a lambda to a variable of type Func<TInput, TOutput> lets you call it exactly like a regular method afterward. Func<int, int> square = n => n * n; declares square as a function that takes an int and returns an int, and square(6) calls it just like any named method would be called.