Displaying an Array's Data as a Delimited String

Displaying an Array's Data as a Delimited String


You have an array or type that implements ICollection, and you wish to display or store it as a string delimited by commas or some other delimiting character. This ability will allow you to easily save data stored in an array to a text file as delimited text.


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)
	    StringBuilder delimitedData = new StringBuilder();

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


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


The following TestDisplayDataAsDelStr method shows how to use the Convert-CollectionToDelStr 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, ',');

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


Of course, instead of a comma as the delimiter, you 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. String.Split works only with delimiters that consist of one character.

See Also

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

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows