【C#】干掉for循环
2010-09-30 22:45:20 来源:WEB开发网 [Test]
public void OldSum()
{
int sum0 = 0;
for (int i = 0; i < 10; i++)
{
sum0 += i;
}
Assert.AreEqual(45, sum0);
}
[Test]
public void NewSum()
{
int sum1 = Enumerable.Range(0, 10).Sum();
int sum2 = Enumerable.Range(0, 10).Aggregate((x, y) => x + y);
int sum3 = Enumerable.Range(0, 10).Aggregate(0, (x, y) => x + y);
Assert.AreEqual(45, sum1);
Assert.AreEqual(45, sum2);
Assert.AreEqual(45, sum3);
}
注:无论是对一串数字求和还是求积,归根到底,都是把一串东西变成一个东西,此时就用Aggregate!
[Test]
public void OldFilter()
{
int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> odd_list = new List<int>();
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] % 2 == 1)
{
odd_list.Add(arr[i]);
}
}
int[] odd_arr = odd_list.ToArray();
Assert.That(odd_arr, Is.EquivalentTo(new int[] { 1, 3, 5, 7, 9 }));
}
[Test]
public void NewFilter()
{
int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] odd_arr = arr.Where(x => x % 2 == 1).ToArray();
Assert.That(odd_arr, Is.EquivalentTo(new int[] { 1, 3, 5, 7, 9 }));
}
- ››FOREACH 宏之GCC实现
- ››循环不间断向上滚动的文本特效代码
- ››ForeFront让企业VPN连接高枕无忧
- ››Forefront TMG日志记录功能
- ››Forefront Security For Exchange文件传送限制测试...
- ››Forefront Security For Exchange关键字测试
- ››Forefront Security For Exchange的反病毒测试
- ››Forefront Security For Exchange部署指南
- ››Forrester:惠普数据中心自动化解决方案最佳
- ››循环链表实验
- ››Forte for Java简介与基础安装
- ››for 语句
赞助商链接