Dave Burke - Freelance .NET Developer specializing in Online Communities

A freelance .NET Developer

Handling the comma. Period.

One of my favorite words for as long as I can remember is "minutia" (or "minutiae" plural.)  My blog is filled with minutiae, and would have been more aptly titled ".NET Minutiae and Very Little Else."  That title might be taken, of course... 

I'm not obsessed with economic code, but I like to write about it when it happens.  Kind of like when my dog scares up a wild turkey from out of some brush during our lunchtime walks.  I tell you about that, but I don't want to take focus off the comma.

Traditionally the approach would be something like

string comma = ", ";
int i = 0;
while (dr.Read())
{
 if (i==0) 
  user_names += dr["user"].ToString();
 else
  user_names += comma + dr["user"].ToString();
 i++;
}

but the new and improved version is

string comma = "";
while (dr.Read())
{
 team_uids += comma + dr["uid"].ToString();
 comma = ", ";
}

Now some stud will show me how this can be improved.  Always happens (which is pretty darn cool!), so check the comments in 24.

Comments

Bill Rodenbaugh said:

i don't know if i would do it this way... but you could :)

while ( dr.Read() )
team_uids = String.Format("{0}{1}{2}", team_uids, ( team_uids.Length > 0 ) ? ", " : String.Empty, dr["uid"]);
# April 28, 2004 4:27 PM

Dave Burke said:

Love it. Thanks, Bill!

# April 28, 2004 4:31 PM

Matt Hawley said:

never thought of using it in the second way, I usually have:

string team_uids = "";
while(dr.Read())
{
if(team_uids != "")
team_uids += ", ";
team_uids += dr["uid"].ToString();
}
# April 28, 2004 4:47 PM

Dave Burke said:

Matt, me too. The fact that there was no if() statement made it "blogworthy."
# April 28, 2004 4:59 PM

AndrewSeven said:

try a StringBuilder ...
# April 28, 2004 5:18 PM

Ryan A. Rinaldi said:

I normally just do it in-line:
while(dr.Read())
{
team_uids += (team_uids == "" ? "" : ", ") + dr["uid"].ToString();
}

I might have syntactical errors since writing code in a textarea is not the easiest thing to do. :)


# April 28, 2004 5:41 PM

Darren Neimke said:

System.Text.StringBuilder sb = new System.Text.StringBuilder() ;

while reader.Read() {
sb.Append( reader["myField"] + "," ) ;
}

string out = sb.ToString() ;
return out.Substring( 0, out.LastIndexOf( ',' ) ) ;
# April 28, 2004 6:50 PM

Dave Burke said:

out.LastIndexOf(','). I'll remember that, Darren. Thx!
# April 28, 2004 7:20 PM

secretGeek said:

This one has other side-effects -- but the side-effects may actually suit your purposes:

Dim comma As String = ", "
team_uids = comma
Do While (dr.Read())
team_uids &= comma & dr("uid").ToString()
Loop
team_uids = team_uids.Replace(comma & comma, "")

Rather than lean toward terseness as happens above, i thought I'd try for verbosity:

Dim comma As New CommaHelper 'defined below
Do While (dr.Read())
team_uids &= comma.ToString & dr("uid").ToString()
Loop

Public Class CommaHelper
Dim _sComma As String = ""
Public Overrides Function toString() As String
Return _sComma
_sComma = ", "
End Function
End Class


# April 28, 2004 7:45 PM

Dave Burke said:

And the scary thing is I could actually follow along. Took me a while to get through it though. Thanks, SG! I enjoyed the, uh, read!
# April 28, 2004 9:19 PM

Brendan Tompkins said:

My approach would be similar to Ryans:

string team_uids = String.Empty;

while(dr.Read())
{
team_uids += (team_uids.Length > 0) ? ", " + dr["uid"].ToString() : dr["uid"].ToString();
}
# April 29, 2004 9:39 AM

Dave Burke said:

Brendan, if team_uids.Length > 0. Ahhh, yes. Like it! Thanks!
# April 29, 2004 9:46 AM

Dylan said:

I still really like Dave's original code. I've always done the
out.Substring( 0, out.LastIndexOf( ',' ) ) ;
approach.

I don't really like the team_uids.Length > 0 because it would take more processing to check length for each step in the loop. Wouldn't matter in .NET, but I do a lot of Flash Actionscript, where every little thing makes a difference with its limited processing power.
# April 29, 2004 12:23 PM

Roy Osherove said:

Um.. you could also use a cleaner approach at the end of the loop:
out.TrimEnd(',')
# April 29, 2004 5:44 PM

TrackBack said:

# April 29, 2004 9:59 PM

AT said:

Hey !! What you are all doing ?? String is imutable and any manipulations with it is BIG NO-NO ...

Use only StringBuilder to work with data and convert to string only after everything is done.

---
StringBuilder sb = new StringBuilder();

foreach (String item in items)
{
sb.Append(item); // Never use string concat here
sb.Append(',');
}

if (sb.Length > 0)
{
sb.Length--;
}

string ret = sb.ToString();

---
# April 29, 2004 10:36 PM

TrackBack said:

# April 29, 2004 11:23 PM

Scott Mitchell said:

Not the most efficient, but how about:

ArrayList a = new ArrayList();
while (dr.Read)
{
a.Add(dr["foo"]);
}

string s = String.Join(",", ((string[]) a.ToArray(typeof(string))));

(may be some typos,didn't test it...)
# April 30, 2004 12:38 AM

Jon Galloway said:

If you're iterating a datareader, you prolly pulled it from a database. Which means you could just get the csv list from the db:

DECLARE @Values varchar(500)

SELECT @Values = COALESCE(@Values + ',', '') UserID FROM Users WHERE STATE = 'MO'

SELECT @Values
# April 30, 2004 2:45 AM

Anonymous said:

# April 30, 2004 9:28 AM

Fernando said:

Manydevelopershavehadtowritealoopthatwritesoutacommaseparatedvaluelist.There'salway...

# November 2, 2007 6:21 AM

Jawad said:

We can use System.Configuration.CommaDelimitedStringCollection

For example

Dim objcol As New System.Configuration.CommaDelimitedStringCollection

       objcol.Add("strOne")

       objcol.Add("strTwo")

       objcol.Add("strThree")

       objcol.Add("strFour")

objcol.ToString() 'Output will be "strOne,strTwo,strThree,strFour"

Best of luck

# July 7, 2008 7:51 AM

tmpuzer said:

@AT:

Regarding using StringBuilder for performance benefits... does it really matter?  Seriously I bet in 90% of cases the decision to use StringBuilder is not worth the brain cycles spent making the decision.  Unless you're concatenating hundreds or thousands of strings the performance is likely negligible.  More importantly, I think using string builder hurts readability, and IMHO I would take human performance boost of increased readability during development and maintenance over the runtime perfomance boost any day.

# October 21, 2008 2:11 PM

danieldsmith said:

-tmpuzer:

"Regarding using StringBuilder for performance benefits... does it really matter?"

Just benchmarked the various techniques that people have suggested above, and yes it makes a big difference!

AT's solution is the fastest so far.  Even for a small list of 50 items, AT's version is around 2.5 times faster than the other suggestions.

# January 15, 2009 10:31 AM

boracay hotels said:

how to make a separate list using commas from csv file?

# August 19, 2010 1:57 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)