Generating Comma Separated Values

后端 未结 2 1462
没有蜡笔的小新
没有蜡笔的小新 2021-02-15 02:17

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

相关标签:
2条回答
  • 2021-02-15 02:31

    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.

    0 讨论(0)
  • 2021-02-15 02:52

    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);
    
    0 讨论(0)
提交回复
热议问题