LINQ 查询

版本新特性 / C# 3.0

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

class Program {
    class Employee {
        public string Name { get; set; }
        public string City { get; set; }
        public int Salary { get; set; }
    }

    static List<Employee> Staff() {
        return new List<Employee> {
            new Employee { Name = "Ann", City = "Rome",  Salary = 90 },
            new Employee { Name = "Bob", City = "Paris", Salary = 70 },
            new Employee { Name = "Cid", City = "Rome",  Salary = 50 }
        };
    }

    // *** 以前 ***
    // 过去筛选、排序和汇总每次都要手写,意图淹没在循环里
    static List<string> RichInRomeOld(List<Employee> staff) {
        List<Employee> found = new List<Employee>();
        foreach (Employee e in staff)
            if (e.City == "Rome" && e.Salary > 60) found.Add(e);
        found.Sort(delegate(Employee a, Employee b) { return b.Salary -
                          a.Salary; });
        List<string> names = new List<string>();
        foreach (Employee e in found) names.Add(e.Name);
        return names;
    }

    // *** 在 3.0 版本中 ***
    // 查询是语言的一部分,编译器会检查名称
    static IEnumerable<string> RichInRomeNew(List<Employee> staff) {
        return from e in staff
               where e.City == "Rome" && e.Salary > 60
               orderby e.Salary descending
               select e.Name;
    }

    static void Main() {
        List<Employee> staff = Staff();
        Console.WriteLine(string.Join(", ", RichInRomeOld(staff).ToArray()));
        Console.WriteLine(string.Join(", ", RichInRomeNew(staff).ToArray()));

        // 分组和合计用的是同一种语言
        var byCity = from e in staff
                     group e by e.City into g
                     select new { City = g.Key, Total = g.Sum(e => e.Salary) };
        foreach (var row in byCity)
            Console.WriteLine(row.City + " " + row.Total);

        // 查询只在此构建,首次读取时才运行
        var query = from e in staff where e.Salary > 60 select e.Name;
        staff.Add(new Employee { Name = "Dee", City = "Rome", Salary = 95 });
        Console.WriteLine(query.Count());   // 3:也计入了 Dee
    }
}