C# Lambda expressions: Why should I use them?

后端 未结 15 1084
栀梦
栀梦 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 03:57

    This is perhaps the best explanations on why to use lambda expressions -> https://youtu.be/j9nj5dTo54Q

    In summary, it's to improve code readability, reduce chances of errors by reusing rather than replicating code, and leverage optimization happening behind the scenes.

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

    It saves having to have methods that are only used once in a specific place from being defined far away from the place they are used. Good uses are as comparators for generic algorithms such as sorting, where you can then define a custom sort function where you are invoking the sort rather than further away forcing you to look elsewhere to see what you are sorting on.

    And it's not really an innovation. LISP has had lambda functions for about 30 years or more.

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

    You can also find the use of lambda expressions in writing generic codes to act on your methods.

    For example: Generic function to calculate the time taken by a method call. (i.e. Action in here)

    public static long Measure(Action action)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        action();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }
    

    And you can call the above method using the lambda expression as follows,

    var timeTaken = Measure(() => yourMethod(param));
    

    Expression allows you to get return value from your method and out param as well

    var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));
    
    0 讨论(0)
  • 2020-11-22 04:01

    Lambda expression is a concise way to represent an anonymous method. Both anonymous methods and Lambda expressions allow you define the method implementation inline, however, an anonymous method explicitly requires you to define the parameter types and the return type for a method. Lambda expression uses the type inference feature of C# 3.0 which allows the compiler to infer the type of the variable based on the context. It’s is very convenient because that saves us a lot of typing!

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

    Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the expressions portion of this statement. Microsoft released a entire namespace, System.Linq.Expressions, which contains classes to create expression trees based on lambda expressions. Expression trees are made up of objects that represent logic. For example, x = y + z is an expression that might be part of an expression tree in .Net. Consider the following (simple) example:

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    
    
    namespace ExpressionTreeThingy
    {
        class Program
        {
            static void Main(string[] args)
            {
                Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object
                var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime
                Console.WriteLine(del(5)); //we are just invoking a delegate at this point
                Console.ReadKey();
            }
        }
    }
    

    This example is trivial. And I am sure you are thinking, "This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own. I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator. You could also use it for Bayesian systems, or for genetic programming (AI). A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions (addition, subtrations, etc) to operate on available data. In pre-.Net 3.5 I have had to resort to some scripting language external to C#, or had to use the code-emitting functionality in reflection to create .Net code on the fly. Now I would use expression trees.

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

    I found them useful in a situation when I wanted to declare a handler for some control's event, using another control. To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created.

    private ComboBox combo;
    private Label label;
    
    public CreateControls()
    {
        combo = new ComboBox();
        label = new Label();
        //some initializing code
        combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
    }
    
    void combo_SelectedIndexChanged(object sender, EventArgs e)
    {
        label.Text = combo.SelectedValue;
    }
    

    thanks to lambda expressions you can use it like this:

    public CreateControls()
    {
        ComboBox combo = new ComboBox();
        Label label = new Label();
        //some initializing code
        combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};
    }
    

    Much easier.

    0 讨论(0)
提交回复
热议问题