Lambda表达式 =>(msdn)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lambda表达式
{
    class Program
    {
        static void Main(string[] args)
        {
            Lambda.Go();
            Lambda.Go1();
            Console.ReadKey();
        }
    }

    public class Lambda
    {
        /*下面的示例演示两种查找并显示最短的字符串的长度在字符数组中的字符串。
         *该示例的第一部分将 lambda 表达式 (w => w.Length) words 于数组的每个元素都使用 Min 方法查找最小长度。
         *为了进行比较,该示例的第二部分演示一个较长的解决方案使用查询语法执行相同操作。 */
        public static void Go()
        {
            string[] words = { "cherry", "apple", "blueberry" };

            // Use method syntax to apply a lambda expression to each element
            // of the words array. 
            int shortestWordLength = words.Min(w => w.Length);
            Console.WriteLine(shortestWordLength);

            // Compare the following code that uses query syntax.
            // Get the lengths of each word in the words array.
            var query = from w in words
                        select w.Length;
            // Apply the Min method to execute the query and get the shortest length.
            int shortestWordLength2 = query.Min();
            Console.WriteLine(shortestWordLength2);

        }

        /*下面的代码演示如何编写采用两个参数标准查询运算符 Enumerable.Where 的超加载的 lambda 表达式。
         * 由于 lambda 表达式具有多个参数,必须括在括号中的参数。 第二个参数,index,表示当前元素的索引集合中的。
         * Where  表达式返回长度小于其在数组的索引位置小于的任何字符串。 */
        public static void Go1()
        {
            string[] digits = { "zero", "one", "two", "three", "four", "five", 
            "six", "seven", "eight", "nine" };

            Console.WriteLine("Example that uses a lambda expression:");
            var shortDigits = digits.Where((digit, index) => digit.Length < index);
            foreach (var sD in shortDigits)
            {
                Console.WriteLine(sD);
            }

            // Compare the following code, which arrives at the same list of short
            // digits but takes more work to get there.
            Console.WriteLine("
Example that uses a for loop:");
            List<string> shortDigits2 = new List<string>();
            for (var i = 0; i < digits.Length; i++)
            {
                if (digits[i].Length < i)
                    shortDigits2.Add(digits[i]);
            }

            foreach (var d in shortDigits2)
            {
                Console.WriteLine(d);
            }

        }
    }
}
原文地址:https://www.cnblogs.com/sunhan/p/3542458.html