DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 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:

one,two,three,four,five,six

Of course, instead of a comma as the delimiter, we could also have used a semicolon, dash, or any other character. The delimiter type was made a char because it is best to use only a single delimiting character if you are going to use the String.Split method to restore the delimited string to an array of substrings, as the String.Split method works only with delimiters that consist of one character.

See Also

See the "ICollection Interface" topic in the MSDN documentation.

    [ Team LiB ] Previous Section Next Section