C# Lambda expressions: Why should I use them?

后端 未结 15 1162
栀梦
栀梦 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

    Lambda expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL.

    The following is an example of a LINQ to Objects expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:

    // anonymous delegate
    var evens = Enumerable
                    .Range(1, 100)
                    .Where(delegate(int x) { return (x % 2) == 0; })
                    .ToList();
    
    // lambda expression
    var evens = Enumerable
                    .Range(1, 100)
                    .Where(x => (x % 2) == 0)
                    .ToList();
    

    Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement closures which can allow you to pass local state to the function without adding parameters to the function or creating one-time-use objects.

    Expression trees are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an Expression<T> parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate:

    void Example(Predicate<int> aDelegate);
    

    called like:

    Example(x => x > 5);
    

    becomes:

    void Example(Expression<Predicate<int>> expressionTree);
    

    The latter will get passed a representation of the abstract syntax tree that describes the expression x > 5. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.

    0 讨论(0)
  • 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<string> people = new List<string> { "name1", "name2", "joe", "another name", "etc" };
     string person = people.Find(person => person.Contains("Joe"));
    

    versus

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

    These are functionally equivalent.

    0 讨论(0)
  • 2020-11-22 04:21

    A lambda expression is like an anonymous method written in place of a delegate instance.

    delegate int MyDelagate (int i);
    MyDelagate delSquareFunction = x => x * x;
    

    Consider the lambda expression x => x * x;

    The input parameter value is x (on the left side of =>)

    The function logic is x * x (on the right side of =>)

    A lambda expression's code can be a statement block instead of an expression.

    x => {return x * x;};
    

    Example

    Note: Func is a predefined generic delegate.

        Console.WriteLine(MyMethod(x => "Hi " + x));
    
        public static string MyMethod(Func<string, string> strategy)
        {
            return strategy("Lijo").ToString();
        }
    

    References

    1. How can a delegate & interface be used interchangeably?
    0 讨论(0)
提交回复
热议问题