9.13. Displaying an Array’s Data as a Delimited String

Problem

You have an array or type that implements ICollection, and that you wish to display or store as a comma-delimited string (note that another delimiter character can be substituted for the comma). This ability will allow you to easily save data stored in an array to a text file as delimited text.

Solution

The ConvertCollectionToDelStr method will accept any object that implements the ICollection interface. This collection object’s contents are converted into a delimited string:

public static string ConvertCollectionToDelStr(ICollection theCollection,
  char delimiter)
{
    string delimitedData = "";

    foreach (string strData in theCollection)
    {
        if (strData.IndexOf(delimiter) >= 0)
        {
           throw (new ArgumentException(
           "Cannot have a delimiter character in an element of the array.",
           "theCollection"));
        }

        delimitedData += strData + delimiter;
    }

    // Return the constructed string minus the final 
    //    appended delimiter char.
    return (delimitedData.TrimEnd(delimiter));
}

Discussion

The following TestDisplayDataAsDelStr method shows how to use the overloaded ConvertCollectoinToDelStr method to convert an array of strings to a delimited string:

public static void TestDisplayDataAsDelStr( )
{
    string[] numbers = {"one", "two", "three", "four", "five", "six"} ;

    string delimitedStr = ConvertCollectionToDelStr(numbers, ',');
    Console.WriteLine(delimitedStr);
}

This code creates a delimited string of all the elements in the array and displays it as follows: ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.