DelimitedList - a useful utility class
There are several classes which I have written over the years which have become almost like my own personal BCL when developing .Net projects. I think most people have these classes laying around in some form or fashion. In fact, I have joined a formalized effort led by Steve Wright to make an open source version of this "Toolbox" called nToolbox. While that project is getting off the ground, I figured I might share some of the classes which have been very useful to me personally. If this topic interests you, you can read my previous post where I shared some code which I use to find Controls on an Asp.Net page.
Background
Here is the situation I kept finding myself in - I will use the case of a comma delimited list of items since it is the most common scenario: I want to loop through a list of strings and build a comma delimited list. The code begins something like this:
string[] items = new string[]
{
"Apples",
"Oranges",
"Pears",
"Bannanas"
};
StringBuilder list = new StringBuilder();
foreach (string item in items)
{
list.AppendFormat("{0},", item);
}
Console.WriteLine(list.ToString());
The problem with this is it will produce the following string:
Apples,Oranges,Pears,Bannanas,
Notice that there is a trailing comma on the end. So then I end up having to explicitly remove that last comma by either not adding it on the last iteration through the loop or by removing it after the loop has completed.
DelimitedList
So I wrote a class which will help me produce such lists but without the pain of remembering if there is a comma at the end or not. Although the DelimitedList class defaults to just having a single comma as its delimited, it can actually have any string as a delimited. I have used it in the past to delimited things by pipes '|' and even line breaks which can be useful when you want one item per line. Rewriting the same code above with the delimited list would look like this:
DelimitedList<string> list = new DelimitedList<string>();
foreach (string item in items)
{
list.Add(item);
}
Console.WriteLine(list.ToString());
Now this will produce the expected string:
Apples,Oranges,Pears,Bannanas
The DelimitedList can also work on any type of object (thus the use of Generics) so you can use it with types other than strings: (just for varieties sake, I will use a delimiter other than a comma)
DelimitedList<int> list = new DelimitedList<int>("+");
for (int i = 0; i < 10; i++)
{
list.Add(i);
}
Console.WriteLine(list);
This will produce the following string:
0+1+2+3+4+5+6+7+8+9
You can download the complete code for the DelimitedList class here