O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required