Hiển thị các bài đăng có nhãn Lambda. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn Lambda. Hiển thị tất cả bài đăng

Thứ Hai, 9 tháng 2, 2009

Các biểu thức Lambda trong C# 3.0 (Phần 2)

Trong phần 1 chúng ta đã tìm hiểu về một số các biểu thức Lambda trong C#. Phần 2 này chúng ta sẽ sử dụng các biểu thức Lambda cho dữ liệu động.

Tôi dùng một danh sách Cutomer class như sau :

public class Customer
{
      public int Id;
      public string Name;
      public string City;
      public Customer(int id, string name, string city)
      {
           Id = id;
           Name = name;
           City = city;
      }
}

và bây giờ sử dụng biểu thức Lambda để tìm một khách hàng đặc biệt với tên của "Abe".

class Program
{
       static void Main(string[] args)
       {
              List customers = new List();
              customers.Add(new Customer(1,"Dave","Sarasota"));
              customers.Add(new Customer(2,"John","Tampa"));
              customers.Add(new Customer(3,"Abe","Miami"));
              Customer abe = customers.Find(c => c.Name.Equals("Abe"));
       }
}

Một lần nữa, chúng ta có thể làm cho mọi việc rõ ràng hơn bởi explicity, tôi gán c đó là các loại khách hàng. Bạn có thể viết ở trên như sau:

class Program
{
        static void Main(string[] args)
        {
             List customers = new List();
             customers.Add(new Customer(1,"Dave","Sarasota"));
             customers.Add(new Customer(2,"John","Tampa"));
             customers.Add(new Customer(3,"Abe","Miami"));
             Customer abe = customers.Find((Customer c) =>
             c.Name.Equals("Abe"));
       }
}

Bây giờ chúng ta cùng làm việc với Collection. Hãy chắc chắn rằng bạn đã có một CustomerCollection và chúng ta sẽ tìm kiếm khách hàng trên Collection này. Dưới đây là CustomerCollection của tôi :

public class CustomerCollection : IEnumerable
{
        IEnumerable _customers;

        public CustomerCollection(IEnumerable customers)
        {
                _customers = customers;
        }

        public IEnumerator GetEnumerator()
        {
               foreach (Customer customer in _customers)
                        yield return customer;
        }

       System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
       {
               return _customers.GetEnumerator();
        }
}

Tôi thêm một method mở rộng cho CustomerCollection Class , được gọi là GetCustomer:

public static class CustomerExtensions
{
        public static Customer GetCustomer(this.CustomerCollection customers,
              Predicate isMatch)
        {
               foreach (Customer customer in customers)
                      if (isMatch(customer))
                           return customer;
               return null;
         }
}

Và bây giờ, chúng ta có thể sử dụng các loại CustomerCollection dễ dàng tìm thấy Abe như:

class Program
{
        static void Main(string[] args)
        {
               CustomerCollection collection = GetCustomers();
               // Using my GetCustomer Method Extension...
               Customer abe = collection.GetCustomer(c => c.Name.Equals("Abe"));
         }

         // Pretend We Don't See This :)
         static CustomerCollection GetCustomers()
         {
                 List customers = new List();
                 customers.Add(new Customer(1,"Dave","Sarasota"));
                 customers.Add(new Customer(2,"John","Tampa"));
                 customers.Add(new Customer(3,"Abe","Miami"));

                  return new CustomerCollection(customers);
         }
}

Hoặc theo một cách khác bạn có thể sử dụng Linq để giải quyết va61b đề này:

static void Main(string[] args)
{
         CustomerCollection collection = GetCustomers();
         // LINQ
         var abe = collection.Single(c => c.Name.Equals("Abe"));
}

DangTrung.

Các biểu thức Lambda trong C# 3.0 (Phần 1)

Một ví dụ về Lambda cho tìm kiếm chuỗi các ký tự :

class Program
{
       static void Main(string[] args)
       {
              List names = new List();
              names.Add("Dave");
              names.Add("John");
              names.Add("Abe");
              names.Add("Barney");
              names.Add("Chuck");
              string abe = names.Find(IsAbe);
              Console.WriteLine(abe);
       }
       public static bool IsAbe(string name)
       {
             return name.Equals("Abe");
       }
}

Dùng so sánh chuỗi ký tự bên trong của một function phục vụ cho tìm kiếm.

class Program
{
       static void Main(string[] args)
       {
              List names = new List();
              names.Add("Dave");
              names.Add("John");
              names.Add("Abe");
              names.Add("Barney");
              names.Add("Chuck");
              string abe = names.Find(delegate(string name)
              {
                      return name.Equals("Abe");
             });
            Console.WriteLine(abe);
       }
}

Các biểu thức Lambda :

Các biểu thức Lambda làm cho mọi việc dễ dàng hơn bằng cách cho phép bạn tránh được những phương pháp vô danh và khó chịu:

class Program
{
        static void Main(string[] args)
        {
                List names = new List();
                names.Add("Dave");
                names.Add("John");
                names.Add("Abe");
                names.Add("Barney");
                names.Add("Chuck");
                string abe = names.Find((string name) => name.Equals("Abe"));
                Console.WriteLine(abe);
        }
}

Vì biểu thức Lambda đủ thông minh để suy ra các loại biến, tôi thậm chí không có để explicity đề cập đến tên một chuỗi ở trên. Tôi có thể loại bỏ nó để đơn giản hơn và viết nó như sau:

class Program
{
         static void Main(string[] args)
         {
                List names = new List();
                names.Add("Dave");
                names.Add("John");
                names.Add("Abe");
                names.Add("Barney");
                names.Add("Chuck");
                string abe = names.Find(name => name.Equals("Abe"));
               Console.WriteLine(abe);
       }
}

Thường thì các nhà phát triển sẽ sử dụng 1 tên biến trong biểu thức Lambda chỉ để giữ cho mọi thứ gần gũi. Ở đây chúng ta thay thế tên p cho tất cả.

class Program
{
        static void Main(string[] args)
        {
              List names = new List();
              names.Add("Dave");
              names.Add("John");
              names.Add("Abe");
              names.Add("Barney");
              names.Add("Chuck");
              string abe = names.Find(p => p.Equals("Abe"));
              Console.WriteLine(abe);
       }
}

DangTrung