views:

122

answers:

5

i try to write a query but my query finished 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+=" )";
A: 
        for (int i = 0; i < listMyColumnNames.Count; ++i)
        {
             Text += listMyColumnNames[i] + " nvarchar(500)";
             if (i < listMyColumnNames.Count-1)
                 Text += ", ";
        }
sbi
+3  A: 

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

polygenelubricants
+1 for pointing out *why* the OP code did not work
Fredrik Mörk
+11  A: 

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 alistMyColumnDefarray, thenJoin` 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, ", ");
xtofl
+1, The most underrated function in .NET!
Jan Jongboom
Yes, I always forget about `Join`.
ho1
+1 for a better approach to solve the problem
Fredrik Mörk
+1 I like this a lot.
Barry
A: 

Or you could just remove your Trim call and add `Text = Text.Replace(", )", " )");' at very end.

ho1
A: 

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

openshac