代码改变世界

LAMDA表达式

2017-06-04 17:05  Dirichlet  阅读(266)  评论(0编辑  收藏  举报

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