Suppose we have the following integer list {, 14}. If we want to obtain the factorial of each value in this list, we may write code like this:
class Program
{
static void Main(string[] args)
{
List<long> list = new List<long> { 4, 8, 14 };
var factoriallist = list.Select(n => Factorial(n)).ToList();
}
private static long Factorial(long n)
{
return n == 1 ? n : n * Factorial(n - 1);
}
}
Is there a way to directly write the recursive code in the above Factorial function in the Lambda expression of the Select method? The key is that we need to get ourselves in the Lambda expression and then call ourselves. This can be done easily using MethodBase. GetCurrentMethod (). The specific code is as follows:
static void Main(string[] args)
{
List<long> list = new List<long> { 4, 8, 14 };
var factoriallist = list.Select(
n =>
{
return n == 1 ? n
: n * (long)MethodBase.GetCurrentMethod().Invoke(null, new Object[] { n - 1 });
}).ToList();
}