Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a comma-separated strings in C#

I have an object which holds many values, and some of them (not all values from the object) need to be put in a CSV string. My approach was this:

string csvString = o.number + "," + o.id + "," + o.whatever .... 

Is there is a better, more elegant way?

like image 323
grady Avatar asked Feb 03 '11 09:02

grady


2 Answers

If you put all your values in an array, at least you can use string.Join.

string[] myValues = new string[] { ... }; string csvString = string.Join(",", myValues); 

You can also use the overload of string.Join that takes params string as the second parameter like this:

string csvString = string.Join(",", value1, value2, value3, ...); 
like image 103
Øyvind Bråthen Avatar answered Sep 19 '22 07:09

Øyvind Bråthen


Another approach is to use the CommaDelimitedStringCollection class from System.Configuration namespace/assembly. It behaves like a list plus it has an overriden ToString method that returns a comma-separated string.

Pros - More flexible than an array.

Cons - You can't pass a string containing a comma.

CommaDelimitedStringCollection list = new CommaDelimitedStringCollection();  list.AddRange(new string[] { "Huey", "Dewey" }); list.Add("Louie"); //list.Add(",");  string s = list.ToString(); //Huey,Dewey,Louie 
like image 25
grysik44 Avatar answered Sep 19 '22 07:09

grysik44