IEnumerable to CSV Extension Method

I was talking with a co-worker about an efficient and reusable way to convert a list of objects to a comma-separated list of the objects’ IDs, and we came up with a pretty cool solution using an extension method. I figured I’d share — enjoy!

void Main()
       var x1 = new MyClass { Id = 1 };
       var x2 = new MyClass { Id = 2 };
       var x3 = new MyClass { Id = 3 };

       var myList = new List { x1, x2, x3 };

       var csv = myList.ToCsv();


public class MyClass
       public int Id {get;set;}

public static class MyClassExtensions
       public static string ToCsv(this IEnumerable<MyClass> myClasses)
              return string.Join(",", myClasses.Select(x => x.Id));


Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s