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.)