Blog

Posts written in September 2008.

  • Published on
    -
    1 min read

    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!