学习lamda表达式
Posted 拒马河
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了学习lamda表达式相关的知识,希望对你有一定的参考价值。
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 + 10; } 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 = 0; i < 7; i++) { Person p = new Person() { Name = i + "儿子", Age = 8 - i, }; persons.Add(p); } return persons; } static void Main(string[] args) { List<Person> persons = PersonsList(); persons = persons.Where(p => p.Age > 6).ToList(); //所有Age>6的Person的集合 Person per = persons.SingleOrDefault(p => p.Age == 1); //Age=1的单个people类 persons = persons.Where(p => p.Name.Contains("儿子")).ToList(); //所有Name包含儿子的Person的集合 //1 GuangChaoshi gwl = JieZhang; Console.WriteLine(gwl(10) + ""); //打印20,委托的应用 Console.ReadKey(); //2 GuangChaoshi gw2 = p => p + 10; Console.WriteLine(gw2(10) + ""); //打印20,表达式的应用 Console.ReadKey(); //3 GuangChaoshi2 gw3 = (p, z) => { int zuidixiaofei = 10; if (p < zuidixiaofei) { return 100; } else { return z - p - 10; } }; Console.WriteLine(gw3(10, 100) + ""); //打印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(1, 1, 1, 1) + ""); //打印2 Console.ReadKey(); //5 Func<int, string> gw5 = p => p + 10 + "--返回类型为string"; Console.WriteLine(gw5(10) + ""); //打印‘20--返回类型为string’,z对应参数b,p对应参数a Console.ReadKey(); //6 Func<int, int, bool> gw6 = (p, j) => { if (p + j == 10) { return true; } return false; }; Console.WriteLine(gw6(5, 5) + ""); //打印‘True’,z对应参数b,p对应参数a Console.ReadKey(); } } }
以上是关于学习lamda表达式的主要内容,如果未能解决你的问题,请参考以下文章