I have an object which holds many values, 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 ....
Somehow I think there is a better, more elegant way?
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.
You can use the
string.Join
method to do something likestring.Join(",", o.Number, o.Id, o.whatever, ...)
.edit: As digEmAll said, string.Join is faster than StringBuilder. They use an external implementation for the string.Join.
Profiling code (of course run in release without debug symbols):
string.Join took 2ms on my machine and StringBuilder.Append 5ms. So there is noteworthy difference. Thanks to digAmAll for the hint.
You could override your object's ToString() method:
If you put all your values in an array, at least you can use
string.Join
.You can also use the overload of
string.Join
that takesparams string
as the second parameter like this:If you're using .Net 4 you can use the overload for
string.Join
that takes an IEnumerable if you have them in a List, too: