Today I finally "got" the Func<>
delegate and saw how I could use it to make some of my less readable LINQ queries (hopefully) more readable.
Here's a simple code sample illustrating the above, in a (very) trivial example
List<int> numbers = new List<int> { 1, 5, 6, 3, 8, 7, 9, 2, 3, 4, 5, 6, };
// To get the count of those that are less than four we might write:
int lessThanFourCount = numbers.Where(n => n < 4).Count();
// But this can also be written as:
Func<int, bool> lessThanFour = n => n < 4;
int lessThanFourCount = numbers.Where(lessThanFour).Count();
Can anyone else give any examples of scenarios where they use Func<>
?
(Note that I would not advocate using Func<>
in a scenario as simple as that shown above, it's just an example that hopefully makes the functionality of Func<>
clear.)
I guess there would only be a point in doing this if you were going to be reusing the Func in question in a number of places (and it involved more than trivial logic). Otherwise using the standard way seems much better and perfectly readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With