Use recursion in Lambda expressions

Source: Internet
Author: User

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();
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.