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

  • 相关阅读:
    Libcurl
    Inno Setup教程
    APICloud平台的融云2.0集成
    关于mysql建立索引 复合索引 索引类型
    linux恢复误删除文件-extundelete
    OpenStack QA
    Android之应用程序怎样调用支付宝接口
    NYOJ 22 素数求和问题
    Mycat(5):聊天消息表数据库按月分表实践,平滑扩展
    opencv对图像进行边缘及角点检測
  • 原文地址:https://www.cnblogs.com/dirichlet/p/3262025.html
Copyright © 2011-2022 走看看