October 02, 2008

ToDelimitedString Extension Method

This has probably been done before, but I thought I would post my implementation.

Take a given generic list (or something that implements IEnumerable, and convert it to a delimited string.

First, declare this delegate somewhere:

   1: public delegate string StringValueDelegate<T>(T obj);




 



Next, in a static class, (I have a class called GeneralExtensions for just this sort of thing), add this code.





   1: public static string ToDelimitedString<T>(this IEnumerable<T> list, string delimiter, StringValueDelegate<T> action)


   2: {


   3:     var sb = new System.Text.StringBuilder();


   4:     foreach (var t in list)


   5:     {


   6:         sb.Append(action.Invoke(t));


   7:         sb.Append( delimiter );


   8:     }


   9:     sb.Remove(sb.Length - 1, 1);


  10:  


  11:     return sb.ToString();


  12: }




Now if I have a customer class with a FirstName and LastName properties, like this:





   1: public class Customer


   2: {


   3:    public string Id { get; set; }


   4:    public string FirstName { get; set; }


   5:    public string LastName { get; set; }


   6: }




And I have a list of them, and want to convert them to a coma delimited list, I would do it like this:





   1: var list = new List<Customer>();


   2: list.Add(new Customer { FirstName="Tom", LastName="Bin" });


   3: list.Add(new Customer { FirstName="John", LastName"Doe" });


   4:  


   5: string result = list.ToDelimitedString(",", c => c.FirstName + " " + c.LastName);




The result will look like this: "Tom Bin, John Doe"

No comments: