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 Viktar Karpach