C# Lambda expressions: Why should I use them?

后端 未结 15 1596
栀梦
栀梦 2020-11-22 03:51

I have quickly read over the Microsoft Lambda Expression documentation.

This kind of example has helped me to understand better, though:

delegate in         


        
15条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 04:13

    This is just one way of using a lambda expression. You can use a lambda expression anywhere you can use a delegate. This allows you to do things like this:

    List strings = new List();
    strings.Add("Good");
    strings.Add("Morning")
    strings.Add("Starshine");
    strings.Add("The");
    strings.Add("Earth");
    strings.Add("says");
    strings.Add("hello");
    
    strings.Find(s => s == "hello");
    

    This code will search the list for an entry that matches the word "hello". The other way to do this is to actually pass a delegate to the Find method, like this:

    List strings = new List();
    strings.Add("Good");
    strings.Add("Morning")
    strings.Add("Starshine");
    strings.Add("The");
    strings.Add("Earth");
    strings.Add("says");
    strings.Add("hello");
    
    private static bool FindHello(String s)
    {
        return s == "hello";
    }
    
    strings.Find(FindHello);
    

    EDIT:

    In C# 2.0, this could be done using the anonymous delegate syntax:

      strings.Find(delegate(String s) { return s == "hello"; });
    

    Lambda's significantly cleaned up that syntax.

提交回复
热议问题