The built-in StringCollection, defined in the .NET
Framework's System.Collections.Specialized namespace, is easy to work with
strings, but I wanted the ability to convert a list to/from a string. Take for
instance a comma-separated value string. I wanted the list to have the ability
to convert the comma-separated list to/from a string. I also wanted to work
with other separators as well, such as the vertical bar/pipe (|) or tab (\t),
which you normally see data separated by. Below, an inherited structure adds
these features.
Listing 3
namespace Nucleo.Collections
{
public class StringCollection: StringCollection
{
public void FromCommaSeparatedList(string text)
{
this.FromSeparatedList(text, ",");
}
public void FromSeparatedList(string text, string separator)
{
string[]items = text.Split(separator.ToCharArray());
foreach (string item in items)
{
if (!string.IsNullOrEmpty(item))
this.Add(item);
}
}
public string ToCommaSeparatedList()
{
return ToSeparatedList(",");
}
public string ToSeparatedList(string separator)
{
string list = string.Empty;
for (int i = 0; i < this.Count; i++)
{
if (i != 0)
list += separator;
list += this[i];
}
return list;
}
public static StringCollection FromList(string text, string separator)
{
StringCollection collection = new StringCollection();
collection.FromSeparatedList(text, separator);
return collection;
}
}
}
Note that the class also uses a static method to create a
collection from a list string, using a separator defined by the user. This
class now has the ability to convert a string from/to CSV or other formatted
data.