Before looking at the interview Treasure (C #), I remember a question is printed triangle. Like what:
I remember that it took me a long time to learn C # and it was a method that was not used in LINQ and is now done again using LINQ. Here's the code:
1 intEmpty =Ten;2 for(inti =1; I <= empty; i++)3 {4 foreach(varCinchEnumerable.repeat (" ", Empty-i))5 {6 Console.Write (c);7 }8 foreach(varSinchEnumerable.repeat ("* ", i))9 {Ten Console.Write (s); One } A Console.WriteLine (); - } -Console.WriteLine ("press ENTER to exit"); theConsole.readkey ();
Problem Solving Ideas:
As observed, the left side of the triangle line can be seen as a triangle, as shown in the red triangle:
You can think of a red triangle as a inverted triangle consisting of a string "" space. : a block represents a "" string.
The code can also be written in the style of functional programming (the book calls this syntax a method syntax ):
1 intEmpty =Ten;//empty is the number of *2 for(inti =1; I <= empty; i++)3 {4Enumerable.//overall function: Output space triangle type5Repeat (" ", Empty-i). ToList ().//The Repeat (tresult,int count) function controls the number of spaces per line. 6ForEach (Console.Write);//The action<t> action function, which executes the action function on each element, that is, each element7 //Execute the Console.Write function8 9Enumerable.repeat ("* ", i). ToList (). ForEach (Console.Write);//function Output * Number triangleTen OneConsole.WriteLine ();//Controlling line breaks A}
Recently looked at LINQ programming, see the repeat operator think of the previous program, a handy to write a, deepen the impression.
Refactoring Code:
Extracting the parameters empty and the "*" and the number of rows enables the secondary function not only to output the * triangle, but also to output other types of triangles. such as the + number triangle. The extracted functions are:
1 //Print * Triangle2 Private Static voidPrinttriangle (stringTypechar,intcount)3 {4 intEmpty =count;5 for(inti =1; I <= empty; i++)6 {7Enumerable.repeat (" ", Empty-i). ToList (). ForEach (Console.Write); 8Enumerable.repeat (typechar+" ", i). ToList (). ForEach (Console.Write); 9Console.WriteLine ();//Controlling line breaksTen } One}
Printtriangle ("*", 10); function call, the output is the same as the triangle.
Printtriangle ("+", 10); Printtriangle ("0", 5); the output shows:
Small example of printing an asterisk (*) triangle (C # LINQ implementation)