Click here to Skip to main content
15,886,802 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I would like to create a looping for the following piece of code.
Anyone can help?



C#
string sql = "SELECT TILE = '" + tile[0]
+ " UNION ALL SELECT tile= '" + tile[1] + "'"
+ " UNION ALL SELECT tile= '" + tile[2] + "'"
+ " UNION ALL SELECT tile= '" + tile[3] + "'"
.
.
.
+ " UNION ALL SELECT tile= '" + tile[n-1] + "'"
+ " UNION ALL SELECT tile= '" + tile[n] + "'";


to make it become like

SQL
string sql1 = "SELECT TILE = '" + tile[0]
+ " UNION ALL SELECT '" + tile[1] + "'"

for i=1;i<100;i++)
{
string sql2 = "UNION ALL SELECT tile = tile[i+1];
string sql = sql1+sql2;
}


If i did the loop as shown, it is able to print only the last tile (input from textbox ).
Anyone can help on this?
Posted

Um...There are a few things wrong there.
The one you have noticed is simple:
C#
for i=1;i<100;i++)
{
string sql2 = "UNION ALL SELECT tile = tile[i+1];
string sql = sql1+sql2;
}
Will always exist with the same string, because each time round the loop you overwrite the previous content of sql and sql2 instead of adding to them.
Probably, what you want is closer to:
C#
for i=1;i<100;i++)
{
string sql2 = "UNION ALL SELECT tile = tile[i+1];
string sql1 += sql2;
}
sql += sql1;
But that won't work either because:
1) You are missing the end double quote!
2) You need a space to separate the UNION parts:
C#
for i=1;i<100;i++)
{
string sql2 = " UNION ALL SELECT tile = tile[i+1]";
string sql1 += sql2;
}
sql += sql1;

1) you need a number not a string:
C#
for i=1;i<100;i++)
{
string sql2 = string.Format(" UNION ALL SELECT tile = tile[{0}]", i + 1);
string sql1 += sql2;
}
sql += sql1;


But if you are going to do things like that, I'd strongly suggest you start looking at using a StringBuilder instead of string concatenation!
 
Share this answer
 
Comments
Member 11765602 8-Jul-15 4:47am    
Thanks! I did a slight modification on your code and it's works!
OriginalGriff 8-Jul-15 5:55am    
You're welcome!
You don't have to create more variables, you can simply assign it like

C#
for i=1;i<100;i++)
{
    sql1 += "UNION ALL SELECT tile = '" + tile[i+1] + "';";
}


Make sure you are using proper value for the loop counter.
 
Share this answer
 
v2
Probably a shorter and simple version could be like

C#
string sql = "SELECT TILE = '" + string.Join("' UNION ALL SELECT TILE = '", tile)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900