C# 3.0 – 新功能 – Lambda expressoin


"=>"這個符號除了代表『等於大於』外,在 C# 3.0 語法中也表示 Lambda expression,它可以讓我們的程式碼更少,也可以讓程式的可讀性更高。

詳細說明:

http://msdn2.microsoft.com/en-us/library/bb397687(VS.90).aspx

完整範例:

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

namespace NewLanguageFeatures
{
    public class Customer
    {
        public int CustomerId { get; private set; }

        public string Name { get; set; }
        public string City { get; set; }

        public Customer(int Id)
        {
            CustomerId = Id;
        }

        public override string ToString()
        {
            return Name + "\t" + City + "\t" + CustomerId;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = CreateCustomers();

            Console.WriteLine("Customers:\n");

            var customerDictionary = new Dictionary<Customer, string>();

            foreach (var c in customers)
                customerDictionary.Add(c, c.Name);

            var matches = customerDictionary.FilterBy(
                (customer, name) => name.StartsWith("墩墩"));
           

            foreach (var m in matches)
                Console.WriteLine(m); 
        }

        static List<Customer> CreateCustomers()
        {
            return new List<Customer>
                {
                    new Customer(1) { Name = "波羅實業",          City = "台北市" },
                    new Customer(2) { Name = "湯姆科技",          City = "台中市" },
                    new Customer(3) { Name = "墩墩數位",          City = "高雄市" },
                    new Customer(4) { Name = "摩利光電",          City = "新竹市" },
                    new Customer(5) { Name = "瑞之路邊攤",        City = "花蓮市" }
                };
        }
    }

    public delegate bool KeyValueFilter<K, V>(K key, V value);

    public static class Extensions
    {
        public static List<K> FilterBy<K, V>(
        this Dictionary<K, V> items,
        KeyValueFilter<K, V> filter)
        {
            var result = new List<K>();

            foreach (KeyValuePair<K, V> element in items)
            {
                if (filter(element.Key, element.Value))
                    result.Add(element.Key);
            }
            return result;
        }

        public static List<T> Append<T>(this List<T> a, List<T> b)
        {
            var newList = new List<T>(a);
            newList.AddRange(b);
            return newList;
        }

        public static bool Compare(this Customer customer1, Customer customer2)
        {
            if (customer1.CustomerId == customer2.CustomerId &&
                customer1.Name == customer2.Name &&
                customer1.City == customer2.City)
            {
                return true;
            }

            return false;
        }
    }
}

執行結果:

Customers:

墩墩數位        高雄市  3
Press any key to continue . . .

筆者使用的環境:Windows 2008 RC0 English + Visual Studio 2008

Skip to main content