
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Displaying an Array’s Data as a Delimited String
|
313
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.",
"theCollection"));
}
delimitedData.Append(strData).Append(delimiter);
}
// Return the constructed string minus the final
// appended delimiter char.
return (delimitedData.ToString( ).TrimEnd(delimiter));
}
Discussion
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, ',');
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, you could also have used a semico-
lon, dash, or any other character. The delimiter type was made a
char because it is
best to use only a single delimiting character if ...