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
本文展示了如何利用Lambda表达式简化列表操作,并通过事件处理实现更灵活的交互。详细介绍了使用List<T>类的方法,如FindAll、Sort和ForEach,并提供了将Lambda表达式应用于初始化Predicate<T>、Comparison<T>和Action<T>的例子。此外,文章还演示了如何在控件上添加事件监听,使用Lambda表达式替代委托声明,提高了代码的可读性和简洁性。
4014

被折叠的 条评论
为什么被折叠?



