Uso de expresiones Lambda en C# 3.0

octubre 4, 2007 09:00 by sergio

Aquí dejo un sencillo ejemplo de uso de expresiones Lambda en C# 3.0. Esta en una AppConsole que calcula Combinaciones y Permutaciones de n, r

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Lambda_Samples
{
    class Stat
    {
        static Func < Int64, Int64 > Factorial =
        (x) =>
        {
            Int64 result = x;
            for (int i = 1; i < x; i++)
            {
                result *= x - i;
            }
            return result;
        };

        static Expression < Func < Int64, Int64, Int64 > > exPermutacion =
        (n, r) => Factorial(n) / Factorial(n - r);

        static Func < Int64, Int64, Int64 > Permutacion =
        (n, r) => Factorial(n) / Factorial(n - r);

        static Expression < Func < Int64, Int64, Int64 > > exCombinacion =
        (n, r) => Factorial(n) / (Factorial(r) * Factorial(n - r));

        static Func < Int64, Int64, Int64 > Combinacion =
        (n, r) => Factorial(n) / (Factorial(r) * Factorial(n - r));

        static void Main(string[] args)
        {
            Console.WriteLine("Este AppConsole demuestra un simple ");
            Console.WriteLine("uso de las Expresiones Lambda en C# 3.0");
            Console.WriteLine("Por Sergio Villaneda");
            Console.WriteLine("Calculo de Permutaciones y Conbinaciones de n,r");
            Console.Write("Ingresa n: ");
            Int64 n = Convert.ToInt64(Console.ReadLine());
            Console.Write("Ingresa r: ");
            Int64 r = Convert.ToInt64(Console.ReadLine());
            Console.WriteLine();
            Console.WriteLine("Expresion Permutacion:");
            Console.WriteLine(exPermutacion);
            Console.WriteLine();
            Console.WriteLine("Expresion Combinacion:");
            Console.WriteLine(exCombinacion);
            Console.WriteLine();
            Console.WriteLine("Resultados:");
            Console.WriteLine("nPr = {0}P{1} = " + Permutacion(n, r), n, r);
            Console.WriteLine("nCr = {0}C{1} = " + Combinacion(n, r), n, r);
            Console.ReadLine();
        }
    }


Actualmente calificado con 5.0 por 4 personas

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Publicaciones relacionadas