Click here to Skip to main content
15,886,812 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I would like to output my string as following:

Word, word, word

Currently, I am unable split the string up with the commas. Please advise as to where I may be going wrong – thank you.

What I have tried:

C#
SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {


                        string content = (reader.GetString(0));

                        result = result + string.Join(",", content);


                        //return result;
                    }
                }
                return result;
            }
Posted
Updated 23-Jun-16 11:35am
v2
Comments
Sergey Alexandrovich Kryukov 23-Jun-16 13:15pm    
Split or add? Those are opposite things. :-)
—SA

 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 23-Jun-16 13:17pm    
5ed.
—SA
String.Join takes multiple strings in some form for the second argument, so you need to read all your results into a string list of some sort and then pass that in once to String.Join

C#
List<string> contentResults = new List<string>();

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
    contentResults.Add(reader.GetString(0));
}

result = string.Join(", ", contentResult);
</string></string>
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 23-Jun-16 13:17pm    
5ed.
—SA
Karthik_Mahalingam 23-Jun-16 13:32pm    
Hi Marcus,
it should be contentResults.Add(reader.GetString(0));
Marcus Kramer 23-Jun-16 14:06pm    
Haha... Nice catch. I clearly wrote quicker than my brain could think again.
Karthik_Mahalingam 23-Jun-16 23:33pm    
:)
In addition to above 2 solution, here is the another way of adding comma's
C#
StringBuilder result = new StringBuilder();
 while (reader.Read())
        {
            string content = (reader.GetString(0));
            result.Append(content + ","); ;
        }
        return result.ToString().TrimEnd(',');
 
Share this answer
 
v2
Comments
Richard Deeming 23-Jun-16 14:15pm    
String concatenation in a loop is a great way to destroy the performance of your application. :)

You should be using a StringBuilder instead.
Karthik_Mahalingam 23-Jun-16 23:38pm    
Yes Richard! you are right, it didn't flashed to my mind at that time..
Updated my solution,
Thanks for pointing it out.

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