- Posted by justin on June 27, 2008
Several times I have had the need to take a collection and convert it to a delimited string for displaying in the UI. I have been using the code below that I found on a blog that I have since lost the link to. However, while at the SEVDNUG meeting tonight Rob showed me an easier way to get the same output using LINQ.
Original Code:
public class CollectionUtilities
{
public string Join<T>(string delimiter, IEnumerable<T> items, Converter<T, string> converter)
{
StringBuilder builder = new StringBuilder();
foreach (T item in items)
{
string converted = converter(item);
if (string.IsNullOrEmpty(converted) == false)
{
builder.Append(converted);
builder.Append(delimiter);
}
}
if (builder.Length > 0)
{
builder.Length = builder.Length - delimiter.Length;
}
return builder.ToString();
}
}
New Code:
public class CollectionUtilities
{
public string Join<T>(string delimiter, IEnumerable<T> items, Converter<T, string> converter)
{
return string.Join(delimiter, (items.Where(i => string.IsNullOrEmpty(converter(i)) == false).Select(i => converter(i))).ToArray());
}
}
NUnit Test:
[Test]
public void JoinTest()
{
string[] joins = new string[]{"1", "2", "3", "4"};
string joinTest = new.Join(",", joins, item => item);
Assert.AreEqual("1,2,3,4", joinTest);
joins = new string[] { "1", "", "3", "4" };
joinTest = new CollectionUtilities().Join(",", joins, item => item);
Assert.AreEqual("1,3,4", joinTest);
joins = new string[] { "1"};
joinTest = new CollectionUtilities().Join(",", joins, item => item);
Assert.AreEqual("1", joinTest);
}