Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opportunities to use Func<> to improve code readability

Tags:

.net

lambda

linq

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

like image 589
Richard Ev Avatar asked Dec 10 '22 21:12

Richard Ev


1 Answers

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.

like image 134
Rob West Avatar answered Dec 17 '22 09:12

Rob West