C# Lambda expressions: Why should I use them?

后端 未结 15 1160
栀梦
栀梦 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:18

    Anonymous functions and expressions are useful for one-off methods that don't benefit from the extra work required to create a full method.

    Consider this example:

     List people = new List { "name1", "name2", "joe", "another name", "etc" };
     string person = people.Find(person => person.Contains("Joe"));
    

    versus

     public string FindPerson(string nameContains, List persons)
     {
         foreach (string person in persons)
             if (person.Contains(nameContains))
                 return person;
         return null;
     }
    

    These are functionally equivalent.

提交回复
热议问题