Creating A Comma Delimited String

A little while back I needed to create a comma-delimited string to parse into my SQL Query. My first attempt in creating my comma-delimited string involved using a StringBuilder class and appending a comma at the end of each of my values via a loop. However, I found that my application would error when parsing my comma-delimited string into my SQL query due to the fact a comma was added to the end of my string.

After some research on the MSDN website to solve my problem I found a solution and it was simpler than I thought. The .NET Framework already has a class called CommaDelimitedStringCollection and it is pretty simple to use as the following example shows:

using System.Configuration;
public partial class CommaPage : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Create a collection to parse to CommaDelimitedStringCollection class
        List<string> cars = new List<string>();
        cars.Add("Volvo");
        cars.Add("VW");
        cars.Add("BMW");
        cars.Add("Ford");
        
        //Create instance of CommaDelimitedStringCollection
        CommaDelimitedStringCollection commaCollection 
        = new CommaDelimitedStringCollection() ;
        
        //Iterate through cars collection and add to commaCollection
        foreach (string item in cars)
        {
            commaCollection.Add(item);
        }
        
        //Read out list of values
        Response.Write(commaCollection.ToString());     
    }
}

The output of the example above would be: "Volvo, VW, BMW, Ford".

So pretty much the .NET Framework's CommaDelimitedStringCollection class did all the work for me.

Nice one!

blog comments powered by Disqus

About

Surinder Bhomra is a Web Developer.

He has achieved a BSc in Information Systems in 2006 and since then has been working in the IT industry.

Prior to working in the Web Development industry I have spent 1.5 years working as an IT Systems Analyst providing support for internal company systems.

Working in the Web Development industry has given me the opportunity to expand my current skills and allowing me to work on website projects using ASP, ASP.NET, CSS, HTML and SQL.

StackOverflow Flair

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.

>