Friday, October 7, 2011

Convert an Array List to a comma delimited string


Sometimes we need to Convert an  ArrayList to a comma delimited string.

For  example:

If we have a ArrayList of string value then we usually write the following code


   ArrayList alist=new ArrayList();

   alist.Add("One");
   alist.Add("Two");
   alist.Add("Three");

   string strComma = string.Join(",", (string[])alist.ToArray(Type.GetType("System.String")));       
      Console.WriteLine(strComma);

Output :

One, Two, Three


On other hand for type int of ArrayList  we need to write code like:

   ArrayList alist=new ArrayList();

   alist.Add(1);
   alist.Add(2);
   alist.Add(3);

   string strComma = string.Join(",", (int[])alist.ToArray(Type.GetType("System.Int32")));
       Console.WriteLine(strComma);


Output:

1,2,3


The difference between the types of list is needed to write different code. It actually makes it impossible to write a single function for ALL types of list this way.

But we can handle this if we write a generic method like:


public static string ArrayToString(IList array, string delimeter)
        {
            string outputString = "";

            for (int i = 0; i < array.Count; i++)
            {
                if (array[i] is IList)
                {
                   outputString += ArrayToString((IList)array[i], delimeter);
                }
                else
                {
                    outputString += array[i];
                }

                if (i != array.Count - 1)
                    outputString += delimeter;
            }

            return outputString;
        }

We now just call the function by sending the  ArrayList as a array and delimiter string. It doesn’t need to care about the Type of ArrayList

Example:

   ArrayList alist=new ArrayList();

   alist.Add(1);
   alist.Add(2);
   alist.Add(3);

  string strComma =ArrayToString(alist.ToArray(),",");
  Console.WriteLine(strComma);

Output:
1,2,3