Generating Comma Separated Values

后端 未结 3 1705
离开以前
离开以前 2021-02-15 01:56

Suppose I have a collection of strings:

\"foo\"
\"bar\"
\"xyz\"

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

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-15 02:47

    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 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), 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.

提交回复
热议问题