【转】LAMDA表达式学习

转自: http://www.cnblogs.com/TeyGao/archive/2012/08/14/2638859.html

很不错的解释

1. 普通绑定:

public void button1_Click(object sender, EventArgs e)
{
     MessageBox.Show("ok");
}

this.button1.Click += button1_Click;

 2. 匿名委托:

this.button1.Click += delegate(object sender, EventArgs e)
{
       MessageBox.Show("Click");
};

 3. LAMDA表达式:

this.button1.Click += ((sender, e) =>
       {
                MessageBox.Show("Click");
        }
);

 编译器会自动推算出表达式中的类型。

 

4. 过滤条件

List<User> users = new List<User>();
 Func<User, bool> predicate = (
        (user) =>
        {
              return user.UserId > 100;
         }
 );
List<User> temps = users.Where(predicate).ToList();

 等同于:

List<User> temps = users.Where(p => p.UserId > 100).ToList();

 

List<User> temps = (from p in users where p.UserId > 100 select p).ToList();

 

List<User> users = new List<User>();
Func<User, bool> predicate = (
     (user) => user.UserId > 100
);
List<User> temps = users.Where(predicate).ToList();

 单挑语句时不需要使用{},同时可以不使用return来返回结果。

5. 排序:

List<User> users = new List<User>();
List<User> temp1 = users.OrderBy(p=>p.UserId).ToList();
Func<User, int> orderby = (user => user.UserId);
List<User> temp2 = users.OrderBy(orderby).ToList();

 

猜你喜欢

转载自7708801314520.iteye.com/blog/2230480