Clever 5x5 grid of alphabets in C#
I have to print a 5x5 table with alphabets in them, like:
<table>
&开发者_如何转开发lt;tr> <td>A</td> <td>B</td> <td>C</td> <td>D</td> <td>D</td>
etc.. the letters are in fact a link, so they will be like:
<td> <a href='/someplace'>A</a> </td>
Those links have all the tendency to change often and I don't fancy hard-coding them and replacing them since they will be appearing in quite a few pages. So I thought I would write up a function to output the whole structure.
Yes, it's pretty straight forward, get the for
loop to behave like:
StringBuilder alphabets = new StringBuilder("<table class='table'>");
for(int i=65; i<=87; i++)
{
//Do stuff here to calculate if i mod 5 is zero and add <tr> accordingly.
//Use Convert.ToChar(i); to get the wanted structure.
}
Then it hit me, I could possibly do it in a better, "clever" way using nested for loops,
for(i=1; i<=5; i++)
{
alpbahets.Append("<tr>")
for(j=1; j<5; j++)
{
//Get the <a > link string here.
}
alphabets.Append("</tr");
}
Now the question is, what can I do to relate i
AND j
to get them into the range of 65-87?
(A-W, since it's a 5x5 grid I will skip the last iteration and manually add YZ
in one td
).
I have tried (i*10 + j) + 54)
(yea, I don't know what I was thinking), but it doesn't work.
This might be an EXTREMELY stupid question, sorry, but what is the way to get this done in nested for
loops? Or is there any other better way? I am asking because I am very curious to know more (and dumb that I already don't).
What about just introducing a variable char letter = 'A';
out side your loops?
Then after using it, call letter++;
to move to the next letter in the alphabeth.
This will make your program more readable also, and won't force other programmers to see some calculation including i and j that ends up as a letter.
Simplicity is often the best solution :)
for(i=0; i<5; i++)
{
alpbahets.Append("<tr>")
for(j=0; j<5; j++)
{
int val = 65 + i*5 +j;
//get the <a > link string here
}
alphabets.Append("</tr");
}
I say go for the simple char option already suggested,
That said it can also be done in the loop like this, though its not the most readable code I've ever written.
StringBuilder alphabets = new StringBuilder("<table class='table'>");
for(int i=0; i<=5; i++)
{
alphabets.Append("<tr>\n");
for(int j=0; j<5; j++)
{
alphabets.Append("<td><a href=\""+"linkGoesHere"+"\">"+ (65+i*5+j<91?Convert.ToChar(65+i*5+j):' ') +"</a></td>\n");
}
alphabets.Append("</tr>");
}
alphabets.ToString().Dump();
Note the ternary operator to ensure the last few cells are blank rather than special characters.
Use zero based indices for i and j and then the formula:
int x = (i*5) + j + 65;
if (x<=87)
printCharacter(x);
If you could output these as floated divs inside a container, rather than as table cells, you could then use a repeater control on the front end (containing a single floated div) and bind the repeater to an array of your required letters (takes care of Y and Z as well).
精彩评论