C# 简单学会Lambda表达式

实际上Lambda表达式是一个方法,只是匿名了而已,Lambda表达式很好地实现简化了匿名函数的委托,代码一般都是:(参数)=>{操作},在写Lambda表达式之前先通过委托来慢慢讲解,讲错勿喷,大神请绕路

1.先实现委托功能

class Program
    {
        delegate void MyDelegate(string str);

        static void Main(string[] args)
        {
            MyDelegate del = new MyDelegate(D1);
            del("实现委托");
            Console.ReadKey();
        }

        public static void D1(string str)
        {
            Console.WriteLine(str);
        }
    }

2.这段代码可以简化成用Lambda表达来写

 class Program
    {
        delegate void MyDelegate(string str);

        static void Main(string[] args)
        {
            MyDelegate del = str =>  Console.WriteLine(str);
            del("实现委托");
            Console.ReadKey();
        }
    }

   如果用Lambda表达式,可以更省代码地实现功能,代码中=>前面的str代表着传入的值,也就是参数,当然,也可以没有参数,后面则是要实现的功能,也就是个方法体,传入的值不用指定类型。则:

=> 前面的srt              ——>   参数,可有可无,可以是多个参数

=>后面实现的功能   ——>   方法体,实现的功能

上面的例子是无返回值的,若需要返回值,请看下面例子:

 class Program
    {
        delegate int MyDelegate(int value1,int value2);

        static void Main(string[] args)
        {
            MyDelegate del = (x,y) => x * y;
            int Result = del(5,6);
            Console.WriteLine("计算结果是:"+Result);
            Console.ReadKey();
        }
    }

    下面用Lambda实现将int[]里面的值大于50的打印出来

class Program
    {
        delegate void MyDelegate(int[] Values);
        static int[] num = { 4, 9, 76, 20, 10, 34, 54, 80 };

        static void Main(string[] args)
        {

            IEnumerable<int> collection = num.Where(num => num > 50);
            foreach (var item in collection)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }

   其实上面的代码也可以用纯Linq来进行实现,对比一下两种写法:

  class Program
    {
        static int[] num = { 4, 9, 76, 20, 10, 34, 54, 80 };

        static void Main(string[] args)
        {
            IEnumerable<int> col = from num in num where num > 50 select num;
            foreach (var item in col)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }

很多时候Linq与Lambda会一起使用到

猜你喜欢

转载自blog.csdn.net/Why_n/article/details/81451959