加菲猫

博客园 首页 新随笔 联系 订阅 管理

using System;
//using System.Linq;
using System.Collections.Generic;

class Customer
{
    // C#3.0 Feature:  Auto-Implemented Properties
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
}

public delegate TResult Func<TArg, TResult>(TArg c);

static class Query
{
    // C#3.0 Feature:  Extension Methods
    public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T,bool> filter)
    {
        foreach (var item in source)
            if (filter(item))
                yield return item;
    }

    public static IEnumerable<TResult> Select<TSource,TResult>(this IEnumerable<TSource> source, Func<TSource,TResult> selector)
    {
        foreach (var item in source)
            yield return selector(item);
    }
}

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

        // C#3.0 Feature:  Query Expressions
        var query = from c in customers
                    where c.City == "London"
                    // C#3.0 Feature:  Anonymous Types
                    select new { c.CustomerID, c.ContactName };

        // C#3.0 Feature:  Lambda Expressions
        //var query = Query.Select(Query.Where(customers, c => c.City == "London"),
        //                         c => new { c.CustomerID, c.ContactName });

        //var query = customers.Where(c => c.City == "London")
        //                     .Select(c => new { c.CustomerID, c.ContactName });

        foreach (var item in query)
            Console.WriteLine("{0}, {1}", item.CustomerID, item.ContactName);
    }

    private static List<Customer> LoadCustomers()
    {
        // C#3.0 Feature:  'var' - Local Variable Type Inference
        // C#3.0 Feature:  Collection Initializers
        var customers = new List<Customer>()
        {
            // C#3.0 Feature:  Object Initializers
            new Customer { CustomerID = "ALFKI", ContactName = "Maria Anders", City = "Berlin"},
            new Customer { CustomerID = "ANATR", ContactName = "Ana Trujillo", City = "México D.F."},       
            new Customer { CustomerID = "WOLZA", ContactName = "Zbyszek Piestrzeniewicz", City = "zawa"}
        };

        return customers;
    }
}

posted on 2008-05-26 16:14  bjh  阅读(353)  评论(0编辑  收藏  举报