## 你能指出这个 ForEach 扩展方法中的错误吗？

2011-10-07 16:06  鹤冲天  阅读(4955)  评论(32编辑  收藏  举报

# 带返回值的 ForEach 扩展

Linq 中没有原生的 ForEach 扩展方法，我们可以很轻松的扩展一个：

 1 2 3 public static void ForEach(this IEnumerable source, Action action) { foreach (var element in source) action(element); }

 1 2 3 4 public static IEnumerable ForEach(this IEnumerable source, Action action) { foreach (var element in source) action(element); return source; }

# 通过单元测试查找错误

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class Employee { public string Name { get; set; } public decimal Bonus { get; set; } } [TestMethod()] public void ForEachTest() { var employees = new Employee[] { new Employee{ Name = "张三", Bonus = 500 }, new Employee { Name = "李四", Bonus = 800} }; var actualBonus = employees .ForEach(e => e.Bonus += 200) .First(e => e.Name == "李四") .Bonus; Assert.AreEqual(1000, actualBonus); }

Enumerable.Range 方法 可以生成整数序列，我们就调用它来作为 source 参数：

 1 2 3 4 5 6 [TestMethod()] public void ForEachTest2() { var nums = Enumerable.Range(1, 10); var actual = nums.ForEach(i => i *= 10).First(); Assert.AreEqual(10, actual); }

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public IEnumerable GetEmployees() { yield return new Employee {Name = "张三", Bonus = 500}; yield return new Employee {Name = "李四", Bonus = 800}; } [TestMethod()] public void ForEachTest3() { var employees = GetEmployees(); var actualBonus = employees .ForEach(e => e.Bonus += 200) .First(e => e.Name == "李四") .Bonus; Assert.AreEqual(1000, actualBonus); }

# 正确实现

 1 public static IEnumerable ForEach(this IEnumerable source, Action action) {/*...*/ }