If you are going to do this sort of thing frequently, then it's worth building your own extension method to do it. The implementation below allows you to do the equivalent of string.Join(", ", arrayOfStrings)
where the arrayOfStrings can be an IEnumerable<T>
, and separator can be any object at all. It allows you to do something like this:
var names = new [] { "Fred", "Barney", "Wilma", "Betty" };
var list = names
.Where(n => n.Contains("e"))
.Join(", ");
Two things I like about this are:
- It's very readable in a LINQ context.
- It's fairly efficient because it uses StringBuilder and avoids evaluating the enumeration twice.
public static string Join<TItem,TSep>(
this IEnumerable<TItem> enuml,
TSep separator)
{
if (null == enuml) return string.Empty;
var sb = new StringBuilder();
using (var enumr = enuml.GetEnumerator())
{
if (null != enumr && enumr.MoveNext())
{
sb.Append(enumr.Current);
while (enumr.MoveNext())
{
sb.Append(separator).Append(enumr.Current);
}
}
}
return sb.ToString();
}