With the introduction of generic delegates in C# 3.0 it is fairly easy to assign lambda expressions to generic delegates and pass those delegates to the extension methods.. Let's take a look at an example of using a few of those generic delegates:
List<int> numbers = new List{ 1, 2, 3, 4, 5, 6, 7 }; Func<int, bool> where = n => n < 6; Func<int, int> select = n => n; Func<int, string> orderby = n => n % 2 == 0 ? "even" : "odd"; var nums = numbers.Where(where).OrderBy(orderby).Select(select);
In the above example, we are using three different extension methods: where, orderby and select. The where extension method takes a generic delegate with int parameter and a return type of boolean to identity if a certain element be included in the output sequence. The select extension method takes an integer parameter and returns an integer, but it could return anything that you want the result to be transformed into — before being sent to the output sequence. In the orderby extension method, we are taking the integer parameter and using it to identify if it is even or odd. Based on that, we sort the results. With the introduction of generic delegates in C# 3.0, it is fairly trivial to assign our lambda expressions to generic delegates and pass those delegates to the extension methods.
Generic delegates allow you to define up to 4 parameters and 1 return type so you can have a delegate that may look something like this:Func<int, bool, string, double, decimal> test;Read more>>
No comments:
Post a Comment