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.

转载于:https://www.cnblogs.com/gester/p/4870307.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值