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?
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, ...);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With