Generating Comma Separated Values

后端 未结 3 1703
离开以前
离开以前 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:40

    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(",");
    
    0 讨论(0)
  • 2021-02-15 02:41

    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)
  • 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<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)
提交回复
热议问题