How can i trim or remove " , " at the end of my query?
i try to write a query but my query finished 开发者_JS百科with "Control nvarchar(500), ". i want to finish "Control nvarchar(500)" How can remove ",", " "?
void SqlTable(List listMyColumnNames, string TableName)
{
string Text = "Create table ENG_"+TableName+" (ENG_"+TableName+"_ID integer PRIMARY KEY identity(1,1), ";
char[] MyChar = {',', ' ' };
for (int i = 0; i < listMyColumnNames.Count; )
{
Text+=listMyColumnNames[i]+" nvarchar(500), ";
if (i == listMyColumnNames.Count-1)
Text.TrimEnd(MyChar);
i++;
}
Text+=" )";
I think you may want to look at String.Join
. What you can do is transform your column name strings, containing the SQL definition of your colum, e.g. MyColumnName[1]+" nvarchar(500)", into a
listMyColumnDefarray, then
Join` that array with the comma as a separator.
The benefit:
- no 'if I'm the last entry',
- clear separation of your column names and your SQL representation for a column
The drawbacks.... none :)
for( String name in listMyColumnNames ) {
listMyColumnDefs.Add( name + " nvarchar(500)" );
}
String mycolumndef = String.Join( listMyColumnDefs, ", ");
There are many ways to fix this, but here's the problem in your code:
if (i == listMyColumnNames.Count-1)
Text.TrimEnd(MyChar); // doesn't work like this!
String
is immutable: you can't invoke a method on it and expect it to be mutated by the method. TrimEnd
instead returns a new String
, so what you need to do is:
Text = Text.TrimEnd(MyChar); // now works fine!
Related questions
- Why string.Replace(“X”,“Y”) works only when assigned to new string?
for (int i = 0; i < listMyColumnNames.Count; ++i)
{
Text += listMyColumnNames[i] + " nvarchar(500)";
if (i < listMyColumnNames.Count-1)
Text += ", ";
}
Or you could just remove your Trim call and add `Text = Text.Replace(", )", " )");' at very end.
Have you thought about using the StringBuilder object to build your string, rather than concatenating yours string in a loop!
http://www.yoda.arachsys.com/csharp/stringbuilder.html
精彩评论