using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions; namespace 阐述lambda
{
class Program
{
delegate int GuangChaoshi(int a);
/// <summary>
/// 委托 逛超市
/// </summary>
/// <param name="a">花费</param>
/// <param name="b">付钱</param>
/// <returns>找零</returns>
delegate int GuangChaoshi2(int a, int b); //结账
public static int JieZhang(int a)
{
return a + ;
} public class Person
{
public string Name { get; set; }
public int Age { get; set; }
} public static List<Person> PersonsList()
{
List<Person> persons = new List<Person>();
for (int i = ; i < ; i++)
{
Person p = new Person() { Name = i + "儿子", Age = - i, };
persons.Add(p);
}
return persons;
} static void Main(string[] args)
{
List<Person> persons = PersonsList();
persons = persons.Where(p => p.Age > ).ToList(); //所有Age>6的Person的集合
Person per = persons.SingleOrDefault(p => p.Age == ); //Age=1的单个people类
persons = persons.Where(p => p.Name.Contains("儿子")).ToList(); //所有Name包含儿子的Person的集合
//
GuangChaoshi gwl = JieZhang;
Console.WriteLine(gwl() + ""); //打印20,委托的应用
Console.ReadKey();
//
GuangChaoshi gw2 = p => p + ;
Console.WriteLine(gw2() + ""); //打印20,表达式的应用
Console.ReadKey(); //
GuangChaoshi2 gw3 = (p, z) =>
{
int zuidixiaofei = ;
if (p < zuidixiaofei)
{
return ;
}
else
{
return z - p - ;
} };
Console.WriteLine(gw3(, ) + ""); //打印80,z对应参数b,p对应参数a
Console.ReadKey(); //4
//i*j+w*x
ParameterExpression a = Expression.Parameter(typeof(int), "i"); //创建一个表达式树中的参数,作为一个节点,这里是最下层的节点
ParameterExpression b = Expression.Parameter(typeof(int), "j");
BinaryExpression be = Expression.Multiply(a, b); //这里i*j,生成表达式树中的一个节点,比上面节点高一级 ParameterExpression c = Expression.Parameter(typeof(int), "w");
ParameterExpression d = Expression.Parameter(typeof(int), "x");
BinaryExpression be1 = Expression.Multiply(c, d); BinaryExpression su = Expression.Add(be, be1); //运算两个中级节点,产生终结点 Expression<Func<int, int, int, int, int>> lambda = Expression.Lambda<Func<int, int, int, int, int>>(su, a, b, c, d); Console.WriteLine(lambda + ""); //打印‘(i,j,w,x)=>((i*j)+(w*x))’,z对应参数b,p对应参数a Func<int, int, int, int, int> f = lambda.Compile(); //将表达式树描述的lambda表达式,编译为可执行代码,并生成该lambda表达式的委托; Console.WriteLine(f(, , , ) + ""); //打印2
Console.ReadKey(); //
Func<int, string> gw5 = p => p + + "--返回类型为string";
Console.WriteLine(gw5() + ""); //打印‘20--返回类型为string’,z对应参数b,p对应参数a
Console.ReadKey();
//
Func<int, int, bool> gw6 = (p, j) =>
{
if (p + j == )
{
return true;
}
return false;
};
Console.WriteLine(gw6(, ) + ""); //打印‘True’,z对应参数b,p对应参数a
Console.ReadKey();
} }
}