zoukankan      html  css  js  c++  java
  • LAMDA表达式

    LAMDA表达式

    (input parameters) => {statement;}
    

    Lambda 语句的主体可以包含任意数量的语句;但是,实际上通常不会多于两个或三个语句。

    通常不必为输入参数指定类型,编译器可以根据委托类型推理,如下:

    delegate void TestDelegate(string s, int n);
    
    TestDelegate myDel = (s, n )=> { string str = n + " " + "World"; Console.WriteLine(s);  n++;};
    myDel("Hello", 2);

    当然也可以显示指定输入参数的其类型:

    delegate void TestDelegate(string s, int n);
    
    TestDelegate myDel = (string s, int n )=> { string str = n + " " + "World"; Console.WriteLine(s);  n++;};
    myDel("Hello", 1);

    1. 在LINQ之外使用Lambda表达式,能用匿名方法的地方都可以用Lambda表达式。

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // Use a lambda expression to define an event handler.
           this.Click += (s, e) => { MessageBox.Show(((MouseEventArgs)e).Location.ToString());};
        }
    }

    2. 查询中使用Lambda表达式,在where,Linq中使用。
    int[] scores = new int[] { 1, 2, 7, 9, 8, 4, 6, 5 };
    
    foreach (var item in scores.Where(n=>n>6))
    {
        Console.WriteLine(item);
    }
    private static void TotalsByGradeLevel()
    {
        // This query retrieves the total scores for First Year students, Second Years, and so on.
        // The outer Sum method uses a lambda in order to specify which numbers to add together.
        var categories =
        from student in students
        group student by student.Year into studentGroup
        select new { GradeLevel = studentGroup.Key, TotalScore = studentGroup.Sum(s => s.ExamScores.Sum()) };
    
        // Execute the query.   
        foreach (var cat in categories)
        {
            Console.WriteLine("Key = {0} Sum = {1}", cat.GradeLevel, cat.TotalScore);
        }
    }
    /*
         Outputs: 
         Key = SecondYear Sum = 1014
         Key = ThirdYear Sum = 964
         Key = FirstYear Sum = 1058
         Key = FourthYear Sum = 974
    */

    参考文章:

    http://msdn.microsoft.com/zh-cn/library/vstudio/bb397675.aspx

  • 相关阅读:
    二叉树的节点删除
    PHP开启错误日志详细说明
    jsonpath模块
    Gunicorn-配置详解
    Vmware创建虚拟机步骤说明,详细配置解释
    Python multiprocessing使用详解
    Python定时任务框架apscheduler
    Access-Control-Allow-Origin跨域解决及详细介绍
    web安全:x-content-type-options头设置
    sqlalchemy的基本操作大全
  • 原文地址:https://www.cnblogs.com/dirichlet/p/3262025.html
Copyright © 2011-2022 走看看