CsvExtensionToCsv Method

Converts the contents of data to a comma-separated values String (CSV, RFC 4180).

Definition

Namespace: FolkerKinzel.CsvTools
Assembly: FolkerKinzel.CsvTools (in FolkerKinzel.CsvTools.dll) Version: 2.0.1+2345335399184346d9b2cc992ed5c814406052c1
C#
public static string ToCsv(
	this IEnumerable<IEnumerable<Object?>?> data,
	char delimiter = ',',
	IFormatProvider? formatProvider = null,
	string? format = null
)

Parameters

data  IEnumerableIEnumerableObject
The data to convert.
delimiter  Char  (Optional)
The field separator character.
formatProvider  IFormatProvider  (Optional)

The provider to use to format the value.

- or -

A null reference for InvariantCulture.

format  String  (Optional)

A format String to use for all items that implement IFormattable.

- or -

A null reference to use the default format for each item.

Return Value

String
A CSV-String containing the contents of data.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type IEnumerableIEnumerableObject. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).

Remarks

For serialization ToString(String, IFormatProvider) is used if the item implements IFormattable, otherwise ToString.

Example

C#
using FolkerKinzel.CsvTools;

namespace Examples;

internal static class CsvStringExample
{
    public static void ConvertingCsvStrings()
    {
        object?[][] data =
        [
            [ "Color", "Direction", "Number"],
            [ "brown", "right", 0],
            ["red", "left", 42],
            [null, "Somewhere \"over\" the Rainbow"],
            ["""
             Blue
             in 
             Green
             """, "Up, or down", -3.14]
        ];

        string csv = data.ToCsv();

        Console.WriteLine(csv);
        Console.WriteLine();

        CsvRecord[] results = Csv.ParseAnalyzed(csv);

        foreach (CsvRecord record in results)
        {
            Console.WriteLine(record);
        }
    }
}

/*
Console Output:

Color,Direction,Number
brown,right,0
red,left,42
,"Somewhere ""over"" the Rainbow",
"Blue
in
Green","Up, or down",-3.14

Color: brown, Direction: right, Number: 0
Color: red, Direction: left, Number: 42
Color: , Direction: Somewhere "over" the Rainbow, Number:
Color: Blue
in
Green, Direction: Up, or down, Number: -3.14
*/

Exceptions

ArgumentNullExceptiondata is null.
ArgumentOutOfRangeExceptiondelimiter is either the double quotes " or a line break character ('\r' or '\n').

See Also