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();

       Console.WriteLine(csv);
}

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));
       }
}

/*
Result:
1,2,3
*/
Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

Leave a comment

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: