zoukankan      html  css  js  c++  java
  • Part 99 Lambda expression in c#

    class Program
        {
            static void Main(string[] args)
            {
                List<Person> persons = new List<Person>() { 
                    new Person{ID=101,Name="lin1"},
                    new Person{ID=102,Name="lin2"},
                    new Person{ID=103,Name="lin3"}
                };
    
                Person person = persons.Find(
                    delegate(Person p)          //this is an anonymous method.
                    {
                        return p.ID == 101;
                    }
                    );
                Person p1 = persons.Find(p=>p.ID==101);//using lambda expression
                Person p2 = persons.Find((Person p)=>p.ID==101);//you can also explicitly the input type but no required
                Console.WriteLine("person id={0},name={1}", person.ID, person.Name);
    
            }
        }
        class Person
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }
    View Code

    => is called lambda operator and read as Goes To. Notice that with a lambda expression you don't have to use the delegate keyword explicitly and don't have to specify the input parameter type explicity. The parameter type is inferred(推倒出来). lambda expressions are more convenient to use than anonymous methods. lambda expressions are particularly helpful for writing LINQ query expressions.

    In most of the cases lambda expressions supersedes(替代) anonymous methods. To my knowlege, the only time I prefer to use anonymous methods over lambdas is, when we have to omit(省略) the parameter list when it's not used within the body.

    Anonymous methods allow the parameter list to be omitted entirely when it's not used within the body,where as with lambda expressions this is not the case.

    For example, with anonymous method notice that we have omitted the parameter list as we are not using them within the body

    Button.Click += delegate{MessageBox.Show("hello world.");};

    The above code can be rewritten using lambda expression as shown below.Notice that with lambda we cannot omit the parameter list.

    Button.Click+=(sender,e)=>{MessegeBox.Show("hello world.");};
    Button.Click+=()=>{MessegeBox.Show("hello world.");};//if omit parameter list it will get a compilar error.
  • 相关阅读:
    JQuery实现1024小游戏
    Windows Server2008 R2安装wampserver缺少api-ms-win-crt-runtime-l1-1-0.dll解决方案
    ASP.NET MVC 邮件发送的功能(微软邮箱发送)。
    浅谈撞库防御策略
    极验高并发验证服务背后的技术实现
    2015年国内数据安全事件盘点
    转载——验证码的昨天、今天和明天
    转载——最近百度云盘不提供搜索,闲来无事,玩玩python爬虫,爬一下百度云盘的资源
    SQL 查询语句
    SQL Server 目录
  • 原文地址:https://www.cnblogs.com/gester/p/4870307.html
Copyright © 2011-2022 走看看