Lambda for Dummies…anyone, anyone? I think not

后端 未结 10 1488
迷失自我
迷失自我 2020-12-22 23:45

In my quest to understand the very odd looking \' => \' operator, I have found a good place to start, and the author is very concise and clear:

         


        
10条回答
  •  南笙
    南笙 (楼主)
    2020-12-23 00:32

    As others have said, a lambda expression is a notation for a function. It binds the free variables in the right-hand-side of the expression to the parameters on the left.

    a => a + 1
    

    creates a function that binds the free variable a in the expression (a + 1) to the first parameter of a function and returns that function.

    One case where Lambdas are extremely useful is when you use them to work with list structures. The System.Linq.Enumerable class provides a lot of useful functions that allow you to work with Lambda expressions and objects implementing IEnumerable. For example Enumerable.Where can be used to filter a list:

    List fruits = new List { 
            "apple", "passionfruit", "banana", "mango", 
            "orange", "blueberry", "grape", "strawberry" };
    
    IEnumerable shortFruits = fruits.Where(fruit => fruit.Length < 6);
    
    foreach (string fruit in shortFruits) {
        Console.WriteLine(fruit);
    }
    

    The output will be "apple, mango, grape".

    Try to understand what's going on here: the expression fruit => fruit.Length < 6 creates a function which return true if the parameter's Length property is less than 6.

    Enumerable.Where loops over the List and creates a new List which contains only those elements for which the supplied function returns true. This saves you to write code that iterates over the List, checks a predicate for each element and does something.

提交回复
热议问题