KARPACH

WEB DEVELOPER BLOG

How to create comma separated list in C#?

Very often during development, you need some kind of coma or pipe-separated string. Since .NET 1.0, the framework had string.Join method. So, you can do something like this:

string[] a = new string[] { "Viktar", "Vasya", "Ivan" };
Response.Write(string.Join(",", a));

However, this is not very useful, since you usually don’t have a string array. Usually, you have a list or array of some kind of objects. Let me show you how you can do it .NET 3.5 using LINQ:

List<Person> persons = new List<Person>();
persons.Add(new Person { FirstName = "Viktar", LastName = "Karpach" });
persons.Add(new Person { FirstName = "Vasya", LastName = "Pupkin" });
persons.Add(new Person { FirstName = "Ivan", LastName = "Ivanov" });                       
Response.Write(string.Join(",", (from p in persons select p.FirstName).ToArray()));
Posted on January 14, 2009 by

Comments

Posted on 6/23/2009 02:03:29 AM by Chris

Wow! Cool! simple but useful!

Posted on 7/10/2009 08:58:22 PM by leve

What if words may contain commas?
Doesn’t matter. You are producing list, not parsing it.

Posted on 9/3/2009 05:42:46 AM by Krishnaraj

Really useful. Saved my time from writing custom method. Thank U :)

Posted on 9/7/2009 07:13:12 PM by jose pulido

Thanks, simple and useful.

Posted on 11/2/2009 08:40:15 AM by Nasir

Grt8..Save my time too…one google search

Posted on 7/15/2010 12:08:40 AM by kazim

perfect :)

thanks

Posted on 5/12/2011 09:46:10 PM by Roy

Superb..

Posted on 8/23/2011 07:33:24 PM by Jen

Great - I figured there should be a nice way to achieve what I needed, and here it is :) Thanks!!

Posted on 9/22/2011 04:25:11 AM by Immalee

Worked like a charm! Thanks!

Posted on 10/18/2011 07:20:45 AM by Doug

used it…save me some time - thanks for the tip!

Posted on 7/26/2012 03:16:01 AM by zylfa

how can i come up to an output like this

3,4,5,6 and 7

Posted on 10/18/2012 11:47:33 AM by sykespro

Perfect! Saved me some time..