Example 1
employees.each do |e|
e.doSomething
end
31 employees.ForEach(delegate(Employee e)
32 {
33 e.DoSomething();
34 });
Example 2
managers = employees.select {|e| e.manager?}
36 List<Employee> managers = employees.FindAll(delegate(Employee e)
37 {
38 return e.IsManager == true;
39 });
Example 3
offices = employees.collect {|e| e.office}
43 List<Office> offices = employees.ConvertAll<Office>(delegate(Employee e)
44 {
45 return e.Office;
46 });
Example 4
managersOffices = employees.select{|e| e.manager?}.map {|m| m.office}
48 List<Office> managerOffices = employees.FindAll(delegate(Employee e)
49 {
50 return e.IsManager == true;
51 }).ConvertAll<Office>(delegate(Employee e)
52 {
53 return e.Office;
54 });
Example 5
allManagers = employees.all? {|e| e.manager?}
noManagers = ! employees.any? {|e| e.manager?}
56 bool allManagers = employees.TrueForAll(delegate(Employee e)
57 {
58 return e.IsManager == true;
59 });
60 bool noManager = employees.TrueForAll(delegate(Employee e)
61 {
62 return e.IsManager == false;
63 });
Example 6
sortedEmployees = employees.sort {|a,b| a.lastname <=> b.lastname}
64 employees.Sort(delegate(Employee a, Employee b)
65 {
66 return a.Age.CompareTo(b.Age);
67 });
Example 7
total = employees.inject(0) {|result, e| result += e.salary}
68 double total = 0;
69 employees.ForEach(delegate(Employee e)
70 {
71 total += e.Salary;
72 });
未实现的功能:
1. sortedEmployees = employees.sort_by {|e| e.lastname} 指定sort属性
2. managers, plebs = employees.partition{|e| e.manager?} 多重赋值
可以看出通过C# 2.0对泛型集合提供的新方法以及对匿名方法的支持,使得它也能方便的实现Closure.