lambda表达式1

Lambda表达式

Sample 1
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
public delegate int mydg(int a,int b);
public static class LambdaTest
{
public static int oper(this int a, int b, mydg dg)
{
return dg(a, b);
}
}
class Program
{

static void Main(string[] args)
{
Console.WriteLine(1.oper(2, (a, b) => a + b));

Console.WriteLine(2.oper(1, (a, b) => a - b));

Console.ReadLine();
}
}
}

[/code]
运行结果:
[code]
3
1
[/code]

分析:
1、 public delegate int mydg(int a, int b);
非常重要,代理,Lambda表达式就是delegate
2、 public static int oper(this int a, int b, mydg dg)
静态方法,结合this的使用,可以通过这种方式对已有类添加方法。
不过这里添加的方法是Lambda表达式。
3、1.oper(2, (a, b) => a + b)
实际执行的是LambdaTest.oper(1,2,(a,b)=>a+b);
补充,所有的类的方法基本上都是用这种方式来执行的。


Sample 2
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
public class Person
{

public string username { get; set; }

public int age { get; set; }


public override string ToString()
{

return string.Format("username:{0} age:{1}", this.username, this.age);

}

}


class Program
{

static void Main(string[] args)
{
var persons = new List<Person> {

new Person {username = "a", age=19},

new Person {username = "b", age=20},

new Person {username = "c", age=21},

};
var selectPerson = from p in persons where p.age >= 20 select p.username.ToUpper();
foreach (var p in selectPerson)
Console.WriteLine(p);
Console.ReadLine();

}
}
}
[/code]

分析:
var selectPerson = from p in persons where p.age >= 20 select p.username.ToUpper();
等价于:
var selectPerson = persons.Where(p => p.age >= 20).Select(p => p.username.ToUpper());


2011-6-2 10:17 danny
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值