Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Comma Separated Values

Tags:

string

c#

.net

Suppose I have a collection of strings:

"foo"
"bar"
"xyz"

And I would like to generate a comma separated values from the list into something like:

"foo, bar, xyz"

Notice the lack of ", " at the end.

I am aware that there are dozens of ways to generate this:

  • use for-loop and string.Format() or StringBuilder.
  • use integer counter and remove the ending ", " if the value > 0
  • don't put ", " on the first run
  • etc.

Sample code of what I have right now:

if (strs.Count() > 0)
{
  var sb = new StringBuilder();
  foreach (var str in strs)
    sb.AppendFormat("{0}, ", str);
  return sb.Remove(0, 2).ToString();
}

What is the best code that is highly reusable for the above scenario, and why?

like image 984
Adrian Godong Avatar asked Aug 07 '09 14:08

Adrian Godong


People also ask

How do I convert Excel to comma-separated values?

Type the formula =CONCATENATE(TRANSPOSE(A1:A7)&",") in a blank cell adjacent to the list's initial data, for example, cell C1. (The column A1:A7 will be converted to a comma-serrated list, and the separator "," will be used to separate the list.)

How do I get a Comma Separated Value in a CSV file?

Using the "From Text" feature in Excel Click the Data tab, then From Text. Select the CSV file that has the data clustered into one column. Select Delimited, then make sure the File Origin is Unicode UTF-8. Select Comma (this is Affinity's default list separator).

How do I get comma-separated values in SQL?

How do I get comma separated values in SQL Server? In order to fetch the comma separated (delimited) values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword.


3 Answers

You want to use the string.Join method, which exists in the BCL for this purpose.

Example:

var myArray = new string[] { "one", "two", "three" };
var output = string.Join(", ", myArray);

Or if you're using .NET 3.5, you can do this with any IEnumerable<string> as such:

var output = string.Join(", ", myEnumerable.ToArray());

(Note that this doesn't give the best performance as it requires, although it is clearly still 'O(n)', and should be suitable for almost all cases).

Now, if your enumerable is not of type string (generically an IEnumerable<T>), you can just use the Select method to convert the result into a string, e.g.

var output = string.Join(", ", myEnumerable.Select(e => e.ToString()).ToArray());

I'm not sure if you're dealing with values that may potentially contains commas in themselves, but this can be worked around by enclosing them in quotes (") and escaping the quotes, similarly to the CSV format.

var output = string.Join(", ", items.Select(x => x.Contains(",") ?
    "\"" + x.Replace("\"", "\"\"") + "\"" : x);

Of course, splitting them back up again is a slightly triciker task, which requires a bit of regex.

like image 70
Noldorin Avatar answered Oct 02 '22 21:10

Noldorin


String.Join is the right answer, but in the case of an IEnumerable, Linq is often shorter than a for loop:

someStringCollection.Aggregate((first, second) => first + ", " + second);
like image 31
GlennS Avatar answered Oct 02 '22 21:10

GlennS


As others have said: String.Join is normally the best way to do this. But what if you have just have an IEnumerable rather than an array? Perhaps you have code to enumerate these as you read them from a file using deferred execution. In this case String.Join isn't quite as nice, because you have to loop over the strings twice — once to create the array and once to join it. In that case, you want something more like this:

public static string ToDelimitedString(this IEnumerable<string> source, string delimiter)
{
    string d = "";
    var result = new StringBuilder();

    foreach( string s in source)
    {
       result.Append(d).Append(s);
       d = delimiter;
    } 
    return result.ToString();
}

This will perform almost as well as String.Join, and works in the more general case. Then, given a string array or any other IEnumerable you can call it like this:

string finalStr = MyStrings.ToDelimitedString(",");
like image 26
Joel Coehoorn Avatar answered Oct 02 '22 21:10

Joel Coehoorn