This is not rocket science, but it does do server a good example on how to use the expression on List<T> and event so that you can refer back some point in life.
First, we see List<T> classes has such methods: FindAll which takes a Predicate<T>, Sort takes a Comparison<T> and ForEach takes a Action<T>, below shows the code that uses Lambda expression to initialize the Predicate<T>, Comparision<T> and Action<T>...
Here is the code
public class SampleWithEventsAndLambdaOnList { class Film { public string Name { get; set; } public int Year { get; set; } } public static void DemoSampleWithLambdaOnList() { var films = new List<Film> { new Film { Name = "Jaws", Year = 1975 }, new Film { Name = "Sining 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 }, }; Action<Film> print = film => Console.WriteLine("Name={0}, Year={1}", film.Name, film.Year); films.ForEach(print); films.FindAll(film => film.Year > 1960).ForEach(print); films.Sort((f1, f2) => f1.Name.CompareTo(f2.Name)); films.ForEach(print); } }
Second, let's see the example of adding some log to Control's events. First see the code below.
public class SampleWithEventsAndLambdaOnList { public static void Log(string title, object sender, EventArgs e) { Console.WriteLine("Event: {0}", title); Console.WriteLine(" Sender: {0}", sender); Console.WriteLine(" Arguments: {0}", e.GetType()); foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(e)) { string name = prop.DisplayName; object value = prop.GetValue(e); Console.WriteLine(" {0} ={1}", name, value); } } public static void DemoSamleEventOnList() { Button button = null; //var form = new Form(); //form.Controls.AddRange(new Control[] { // new Label { Text = "Simple Demo Form" }, // button = new Button { Text = "Click Me"} //}); button = new Button { Text = "Click Me" } ; button.Click += (src, e) => Log("Click ", src, e); button.KeyPress += (src, e) => Log("KeyPress", src, e); button.MouseClick += (src, e) => Log("MouseClick", src, e); var form = new Form { AutoSize = true, Controls = { button } }; // the reason why this works is because Controls = { button } will actually transform to // Controls.AddRange(new [] { button } ) // but if you write as such // Controls = new [] { button } // then it is error Application.Run(form); } }
As you can see, you can easily replace the delegate declaration with the lambda expression