C#Lambda教程与案例

Lambda表达式是一个匿名函数,它可以包含表达式和语句,并且可用于创建或表达式目录树类型。
(input parameters)=>expression
语法:左边是输入参数(如果有) 右边包含表达式或者语句块 如:x=>x*x

查询数组的案例

        static void Lind_Lambda()
        {
            string[] strLists = new string[] { "LLT1", "LLT2", "LLT3" };
            string[] strList = Array.FindAll(strLists, s => (s.IndexOf("3") >= 0));
            foreach (string str in strList)
            {
                Console.WriteLine(str);
            }
        }
using System;

namespace Lambda
{
    class Program
    {
        /*Lambda理解与应用
         Lambda 就是匿名方法
         */
        static void Main(string[] args)
        {
            Show1();
            Show2();
            Show3();

            action1();
            action2(DateTime.Now);
            Console.WriteLine(func());

            Console.ReadKey();
        }
        //声明一个委托
        delegate void StudentDelegate(string name, int age);
        //历史1
        static void Student(string name,int age)
        {
            Console.WriteLine($"姓名:{name};年龄:{age}");
        }
       
       static void Show1()
        {
            StudentDelegate studentDelegate = new StudentDelegate(Student);
            studentDelegate.Invoke("小明", 18);
        }

        //历史2
        static void Show2()
        {
            StudentDelegate studentDelegate = new StudentDelegate(delegate (string name, int age)
              {
                  Console.WriteLine($"姓名:{name};年龄:{age}");
              });

            studentDelegate("小红", 20);
        }
        //版本3(=>读成goes to)
        static void Show3()
        {
            StudentDelegate studentDelegate = new StudentDelegate((string name, int age)=>
            {
                Console.WriteLine($"姓名:{name};年龄:{age}");
            });

            studentDelegate("匿名委托", 30);
        }

        //Lambda其他写法
        static Action action1 = () => Console.WriteLine("无返回值,无参数");
        static Action<DateTime> action2 = d => { Console.WriteLine(d + "带一个参数"); };
        static Func<DateTime> func = () =>  DateTime.Now; //带返回值
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值