How to create comma separated list in C#?

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

string[] a = new string[] { "Viktar", "Vasya", "Ivan" };           

Response.Write(string.Join(",", a));

Howerver, this not really useful, since you usually doesn't have string array. Usually you have 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()));


Wednesday, January 14, 2009 | Comments (5) | Add Comment

Comments

Gravatar

Re:How to create comma separated list in C#?

Wow! Cool! simple but useful!

6/23/2009 2:03:29 AM | by Chris
Gravatar

Re:How to create comma separated list in C#?

What if words may contain commas?

7/10/2009 8:58:22 PM | by leve
Gravatar

Doesn't matter. You are producing list, not parsing it.

Gravatar

Re:How to create comma separated list in C#?

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

9/3/2009 5:42:46 AM | by Krishnaraj
Gravatar

Re:How to create comma separated list in C#?

Thanks, simple and useful.

9/7/2009 7:13:12 PM | by jose pulido
Gravatar

Re:How to create comma separated list in C#?

Grt8..Save my time too...one google search

11/2/2009 8:40:15 AM | by Nasir

New Comment

Your Name:
Email (for internal use only):
Subject:
Comment:
 
Code above: