usingSystem;usingSystemCollectionsGeneric;
usingSystemLinq;
usingSystemText;
usingNUnit;
namespaceKSharp
{
[TestFixture]
publicclassTestForLoop
{
[Test]
publicvoidOldSum()
{
intsum=;
for(inti=;i<;i++)
{
sum+=i;
}
AssertAreEqual(sum);
}
[Test]
publicvoidNewSum()
{
intsum=EnumerableRange()Sum();
intsum=EnumerableRange()Aggregate((xy)=>x+y);
intsum=EnumerableRange()Aggregate((xy)=>x+y);
AssertAreEqual(sum);
AssertAreEqual(sum);
AssertAreEqual(sum);
}
[Test]
publicvoidOldFilter()
{
int[]arr=new[]{};
List<int>odd_list=newList<int>();
for(inti=;i<arrLength;i++)
{
if(arr[i]%==)
{
odd_listAdd(arr[i]);
}
}
int[]odd_arr=odd_listToArray();
AssertThat(odd_arrIsEquivalentTo(newint[]{}));
}
[Test]
publicvoidNewFilter()
{
int[]arr=new[]{};
int[]odd_arr=arrWhere(x=>x%==)ToArray();
AssertThat(odd_arrIsEquivalentTo(newint[]{}));
}
[Test]
publicvoidOldMap()
{
int[]arr=new[]{};
List<int>new_list=newList<int>();
for(inti=;i<arrLength;i++)
{
new_listAdd(arr[i]*);
}
int[]new_arr=new_listToArray();
AssertThat(new_arrIsEquivalentTo(newint[]{}));
}
[Test]
publicvoidNewMap()
{
int[]arr=new[]{};
int[]new_arr=arrSelect(x=>x*)ToArray();
AssertThat(new_arrIsEquivalentTo(newint[]{}));
}
[Test]
publicvoidPrintMultiplicationFact()
{
ConsoleWrite(
x=\n
+x=x=\n
+x=x=x=\n
+x=x=x=x=\n
+x=x=x=x=x=\n
+x=x=x=x=x=x=\n
+x=x=x=x=x=x=x=\n
+x=x=x=x=x=x=x=x=\n
+x=x=x=x=x=x=x=x=x=\n
);
/*********************方法一:嵌套循环*************************/
for(intj=;j<;j++)
{
for(inti=;i<;i++)
{
if(i<=j)
{
ConsoleWrite({}x{}={}\tiji*j);
}
}
ConsoleWrite(\n);
}
/*********************方法二:扩展方法*************************/
EnumerableRange()
SelectMany(j=>EnumerableRange()(ji)=>new{ij})
Where(x=>xi<=xj)
Grouy(x=>xj)
Select(g=>gAggregate((ax)=>a+stringFormat({}x{}={}\txixjxi*xj)))
ToList()ForEach(x=>ConsoleWriteLine(x));
/*********************方法三:Linq表达式************************/
(
fromjinEnumerableRange()
fromiinEnumerableRange()
wherei<=j
groupnew{ij}byjintog
selectnew
{
LineNo=gKey
Line=gAggregate((ax)=>a+stringFormat({}x{}={}\txixjxi*xj))
}
)ToList()ForEach(g=>ConsoleWriteLine(gLine));
}
}
}