c# in deep 之Lambda表达式
从很多方面,Lambda表达式都可以看作是C# 2的匿名方法的一种演变。匿名方法能做的几乎一切事情都可以用Lambda表达式来完成,而且其更简洁、易读。下面是一个简单例子。
class Film
{
public string Name { get; set; }
public int Year { get; set; }
}
class Program
{
static void Main()
{
var films = new List<Film>
{
new Film { Name = "Jaws", Year = 1975 },
new Film { Name = "Sing in the Rain", Year = 1952 },
new Film { Name = "Some Like it Hot", Year = 1959 },
new Film { Name = "The Wizard of oz", Year = 1939 },
new Film { Name = "It's a Wonderful Life", Year = 1946 },
new Film { Name = "American Beauty", Year = 1999 },
new Film { Name = "High Fidelity", Year = 2000 },
new Film { Name = "The Usual Suspects", Year = 1995 }
};
Action<Film> print = //创建可重用的列表打印委托
film => Console.WriteLine("Name={0},Year={1}", film.Name, film.Year);
films.ForEach(print); //打印原始列表
Console.WriteLine("---------------------------------------");
films.FindAll(film => film.Year < 1960).ForEach(print);
Console.WriteLine("---------------------------------------");
films.Sort((f1, f2) => f1.Name.CompareTo(f2.Name));
films.ForEach(print);
Console.WriteLine("---------------------------------------");
Console.ReadKey();
}
}