Skip to content

Advanced Usage

Marcus Ackre Medina edited this page Sep 13, 2026 · 1 revision

Advanced Usage

Typed CSV parsing with FromCsv<T>

public static IEnumerable<T> FromCsv<T>(
    this string csv,
    Func<string[], T> mapRow,
    bool hasHeaders = false,
    char delimiter = ',')

Parses a whole CSV document and maps each row (as a string[]) to your own type via a delegate — you control the conversion, including parsing numbers, dates, or skipping columns:

var people = "Name,Age\nAlice,30\nBob,25"
    .FromCsv(row => new Person(row[0], int.Parse(row[1])), hasHeaders: true);

Generating a CSV document from objects with ToCsvDocument<T>

public static string ToCsvDocument<T>(
    this IEnumerable<T> items,
    Func<T, IEnumerable<object?>> mapRow,
    IEnumerable<string>? headers = null,
    char delimiter = ',')

Goes the other direction — takes any collection of objects, a delegate that picks which values become a row, and an optional header row:

var csv = people.ToCsvDocument(
    p => new object?[] { p.Name, p.Age },
    headers: ["Name", "Age"]);

Building XML elements with attributes

ToXmlElement is an extension on the element name (a string), taking the content and an optional attribute collection — easy to get backwards, so note the order:

var attrs = new[] { new KeyValuePair<string, object?>("id", 42) };
string xml = "person".ToXmlElement("Alice", attrs);
// => <person id="42">Alice</person>

Attribute values and element content are escaped automatically via ToXmlContent().

Indented JSON

ToJson<T> defaults to compact, camelCase output, but accepts writeIndented: true for pretty-printed output:

new Person("Alice", 30).ToJson(writeIndented: true);

Validation before parsing

IsValidJson() lets you check a string is parseable JSON before calling FromJson<T>(), so you can branch on malformed input instead of catching a JsonException:

if (payload.IsValidJson())
{
    var person = payload.FromJson<Person>();
}

Clone this wiki locally