lambda运算符

lambda运算符:所有的lambda表达式都是用新的lambda运算符 " => ",可以叫他,“转到”或者 “成为”。运算符将表达式分为两部分,左边指定输入参数,右边是lambda的主体。

lambda表达式:

               1.一个参数:param=>expr

               2.多个参数:(param-list)=>expr

实例

 1 namespace 阐述lambda
 2 {
 3     public class Person
 4     {
 5         public string Name { get; set; }
 6         public int Age  {  get;set; }    
 7     }
 8     class Program
 9     {
10 
11         public static List<Person> PersonsList()
12         {
13             List<Person> persons = new List<Person>();
14             for (int i = 0; i < 7; i++)
15             {
16                 Person p = new Person() { Name = i + "儿子", Age = 8 - i, };
17                 persons.Add(p);                
18             }
19             return persons;
20         }
21 
22         static void Main(string[] args)
23         {
24             List<Person> persons = PersonsList();
25             persons = persons.Where(p => p.Age > 6).ToList();       //所有Age>6的Person的集合
26             Person per = persons.SingleOrDefault(p => p.Age == 1);  //Age=1的单个people类
27             persons = persons.Where(p => p.Name.Contains("儿子")).ToList();   //所有Name包含儿子的Person的集合
28         }
29     }
30 }
知识兔

正常使用和lambda运算符的区别

//委托  逛超市
        delegate int GuangChaoshi(int a);
        static void Main(string[] args)
        {
            GuangChaoshi gwl = JieZhang;
            Console.WriteLine(gwl(10) + "");   //打印20,委托的应用
            Console.ReadKey();
        }
        
        //结账
        public static int JieZhang(int a)
        {
            return a + 10;
        }
知识兔
//委托  逛超市
        delegate int GuangChaoshi(int a);
        static void Main(string[] args)
        {          
           // GuangChaoshi gwl = JieZhang;
            GuangChaoshi gwl = p => p + 10;
            Console.WriteLine(gwl(10) + "");   //打印20,表达式的应用
            Console.ReadKey();
        }
知识兔

还可以多参数和复杂运算

 1 /// <summary>
 2         /// 委托  逛超市
 3         /// </summary>
 4         /// <param name="a">花费</param>
 5         /// <param name="b">付钱</param>
 6         /// <returns>找零</returns>
 7         delegate int GuangChaoshi(int a,int b);
 8         static void Main(string[] args)
 9         {
10             GuangChaoshi gwl = (p, z) =>
11             {
12                 int zuidixiaofei = 10;
13                 if (p < zuidixiaofei)
14                 {
15                     return 100;
16                 }
17                 else
18                 {
19                     return z - p - 10;
20                 }
21            
22             };
23             Console.WriteLine(gwl(10,100) + "");   //打印80,z对应参数b,p对应参数a
24             Console.ReadKey();
25         }
知识兔
计算机