Sum Extension
I am sure those who know about Linq, must have used Sum extension method in their logic, in some way.
A basic example showing the use of Sum extension method.
Ex. Sum up the salary of employees in a generic list
And, why we wouldn't use it. It is powerful & simple to use.
But, have you ever wondered how to mimic the same functionality in your own extension method??
Sounds Interesting, Right !!
Let's get ready for the challenge !!
Let's see how....
I would be creating an extension method named SumEx. The signature would be same, so this version will be totally compatible with the previous example. We will see it in action.
This extension is a perfect example of how to make delegates into work, in a real world use case.
Our extension method is ready now, let put it to test.
As you see the code is perfectly working fine, and results do tally up.
I hope this gives a good idea of how to write an extension method in a way the configuration can be passed from outside. Here, the configuration is which field you want to sum up i.e. Salary & Stock.
Happy Coding !!
Top comments (0)