LINQ Study Note – 01

LINQ works by using extension methods in C#, as LINQ won’t change the IEnumerator behind the scene.


Func and Action

Func type is common when we use LINQ to process, fetch and modify data or data collection in C#. Func itself can take 17 generic types as parameters. The last generic type parameter describes the return type of the function.


Func – Single Parameter

Func<int, int> square = x => x * x;
Console.WriteLine(square(3));

In the above code snippet, We define a Func type, and its name is square. square takes two parameters. The first int is the parameter, and the last one is the return type.

As a result, the square takes a parameter x and return a result of x times x.

Func – Multiple Parameters

Func type does not only take one parameter, but also can take multiple parameters.

Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(9, 6));

In the code snippet above, Func add take two parameters and return a int value. The int value is the sum of the two parameters.


Action Type

Action type always returns void in C#.

Action<string> write = x => Console.WriteLine(x);
write("This is an Action example!");

The code above takes a string type as a parameter and print out the parameter as expected.


Leave a Reply

Your email address will not be published. Required fields are marked *