lambda表达式1
Lambda表达式
Sample 1
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();
}
}
}
运行结果:
3
1
分析: 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
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();
}
}
}
分析: 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