Why CommaDelimitedStringCollection Made Me Happy Today

Another thing that I stumbled on today that has made me all sorts of happy is the CommaDelimitedStringCollection class, which basically let’s you take a bunch of string values and work with them in a comma delimited format (so I guess the class name is pretty intuitive :) ). I can’t even explain how many times I have re-invented this wheel. So let’s say that you have a ListBox control that contains a set of string type values, and you are adding the selected values to a list generic in something like an event handler, you would have this basically:

[csharp]

List m_gBoxGeneric = new List();
foreach (string l_strValue in l_oTbExample.SelectedItems)
{
m_gBoxGeneric.Add(l_strValue);
}

[/csharp]

where the l_oTbExample is just a ListBox control. This isn’t very earthshattering and I am just using that loop as an example. Now, let’s say you want to output those selected values into a comma delimited format. The easiest way to do it is to just use the CommaDelimitedStringCollection class, which natively provides this functionality. It would look like this:

[csharp]

CommaDelimitedStringCollection m_oDelimitedFormat = new CommaDelimitedStringCollection();

List.Enumerator l_oEnumerator = m_gBoxGeneric.GetEnumerator();
try
{
while (l_oEnumerator.MoveNext())
{
string l_strBoxVal = l_oEnumerator.Current;
m_oDelimitedFormat .Add(l_strBoxVal);
}
}
finally
{
l_oEnumerator.Dispose();
}

[/csharp]

Then you can just output the comma delimited values by doing a m_oDelimitedFormat.ToString() and you are done!

Share

One thought on “Why CommaDelimitedStringCollection Made Me Happy Today”

  1. The original version looks much more mature and reasonable, even with the funky Hungarian warts. Sorry, dude – this example does not sell me on this specialized class.

Leave a Reply

Your email address will not be published. Required fields are marked *