Skip to content

Instantly share code, notes, and snippets.

@miklund
Last active January 15, 2016 19:46
Show Gist options
  • Save miklund/eb90cdb497adcef17b13 to your computer and use it in GitHub Desktop.
Save miklund/eb90cdb497adcef17b13 to your computer and use it in GitHub Desktop.
2009-06-12 From list to delimited string
# Title: From list to delimited string
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2009/06/12/from-list-to-delimited-string.html
public static class EnumerableExtensions
{
public static string ToDelimitedString<T>(this IEnumerable<T> list, string separator)
{
return ToDelimitedString(list, separator, DefaultConverter);
}
public static string ToDelimitedString<T>(this IEnumerable<T> list, string separator, Converter<T, string> converter)
{
// List can't be null
if (list == null)
{
throw new ArgumentNullException("list", "Tried to create a string from a list that was null");
}
if (separator == null)
{
throw new ArgumentNullException("separator", "Must specify a separator even if it is string.Empty");
}
Contract.EndContractBlock();
// If converter was null, we probably wanted default converter
if (converter == null)
{
return list.ToDelimitedString(separator, DefaultConverter);
}
// Start the process of creating the string
var sb = new StringBuilder();
foreach (var o in list)
{
sb.Append(converter(o));
sb.Append(separator);
}
/* Remove last seperator (if there is one) */
if (sb.Length > 0)
{
sb.Length -= separator.Length;
}
return sb.ToString();
}
private static string DefaultConverter<T>(T item)
{
return item.ToString();
}
}
public static void Main(string[] args)
{
// Simple example
string[] names = { "Joe", "Jack", "James" };
names.ToDelimitedString(",");
// A bit more complex
var books = new Book[]
{
new Book { Isbn = 1590598504, Title = "Expert F#", Price = 614},
new Book { Isbn = 735619670, Title = "Code Complete", Price = 324},
};
books.ToDelimitedString("\n", book => string.Format("ISBN={0}, Title={1}, Price={2:c}", book.Isbn, book.Title, book.Price));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment