Skip to content

CSV Diff — C# source

Diff two CSVs by a key column: rows added, removed and changed, with the differing columns named. Quoted cells with commas, quotes and newlines are handled. Runs locally with a shareable link.

This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// csv-diff — key-based row diff of two RFC-4180 CSVs. C# port (canonical TS:
// src/lib/csv-diff.ts; Go twin: cli/csv-diff). Mirrors the sibling ports: an
// RFC-4180 parser (quoted cells with embedded commas, quotes and newlines;
// CR dropped; a trailing field without a newline still completes its row)
// with blank single-cell rows dropped as trailing noise, strict per-side
// validation (empty CSV, duplicate columns, ragged rows, duplicate keys —
// the pinned error strings, carried as strings, never exceptions out of the
// entry point), then a key-based diff over the sorted key union:
// added/removed rows and changed rows whose differing column names come out
// sorted.
using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>One row of the diff result; Before/After hold the full records.</summary>
public sealed class RowDiff
{
    public string Key = "";
    public string Type = "";                    // "added" | "removed" | "changed"
    public List<string> Columns;                // differing names on "changed", sorted
    public Dictionary<string, string> Before, After;
}

public sealed class DiffResult
{
    public List<RowDiff> Rows = new List<RowDiff>();
    public bool Same;
    public string Error;                        // null mirrors TS null (success)
}

public static class CsvDiff
{
    /// <summary>RFC 4180 parser mirroring the TS loop: lenient quotes, CR
    /// dropped, a trailing field without a newline still completes its row.</summary>
    static List<List<string>> CsvToRows(string csv)
    {
        var rows = new List<List<string>>();
        var field = new System.Text.StringBuilder();
        var row = new List<string>();
        var inQ = false;
        for (var i = 0; i < csv.Length; i++)
        {
            var ch = csv[i];
            if (inQ)
            {
                if (ch == '"')
                {
                    if (i + 1 < csv.Length && csv[i + 1] == '"') { field.Append('"'); i++; }
                    else inQ = false;
                }
                else field.Append(ch);
            }
            else if (ch == '"') inQ = true;
            else if (ch == ',') { row.Add(field.ToString()); field.Clear(); }
            else if (ch == '\n') { row.Add(field.ToString()); rows.Add(row); row = new List<string>(); field.Clear(); }
            else if (ch != '\r') field.Append(ch);
        }
        if (field.Length > 0 || row.Count > 0) { row.Add(field.ToString()); rows.Add(row); }
        return rows;
    }

    /// <summary>Blank single-cell rows are trailing noise to a diff, not data.</summary>
    static List<List<string>> ParseCsv(string text) =>
        CsvToRows(text).Where(r => !(r.Count == 1 && r[0] == "")).ToList();

    /// <summary>Strict per-side validation → (header, records);
    /// InvalidOperationException carries the pinned strings (empty CSV,
    /// duplicate column, ragged row).</summary>
    static Tuple<List<string>, List<Dictionary<string, string>>> ToRecords(List<List<string>> rows, string label)
    {
        if (rows.Count == 0) throw new InvalidOperationException(label + ": empty CSV");
        var header = rows[0];
        var seen = new HashSet<string>();
        foreach (var name in header)
            if (!seen.Add(name)) throw new InvalidOperationException(label + ": duplicate column \"" + name + "\"");
        var records = new List<Dictionary<string, string>>();
        for (var r = 1; r < rows.Count; r++)
        {
            if (rows[r].Count != header.Count)
                throw new InvalidOperationException(label + ": row " + (r + 1) + " has " + rows[r].Count + " cells, expected " + header.Count);
            var rec = new Dictionary<string, string>();
            for (var c = 0; c < header.Count; c++) rec[header[c]] = rows[r][c];
            records.Add(rec);
        }
        return Tuple.Create(header, records);
    }

    /// <summary>Diff two CSVs by key column (null → the first header column).</summary>
    public static DiffResult Diff(string leftRaw, string rightRaw, string keyColumn = null)
    {
        if (string.IsNullOrWhiteSpace(leftRaw) || string.IsNullOrWhiteSpace(rightRaw))
            return new DiffResult { Error = "Both inputs are required" };
        try
        {
            var left = ToRecords(ParseCsv(leftRaw), "Left");
            var right = ToRecords(ParseCsv(rightRaw), "Right");
            var lheader = left.Item1;
            var key = keyColumn ?? lheader[0];
            if (!lheader.Contains(key)) return new DiffResult { Error = "Left: no key column \"" + key + "\"" };
            if (!right.Item1.Contains(key)) return new DiffResult { Error = "Right: no key column \"" + key + "\"" };
            if (lheader.Count != right.Item1.Count || !lheader.SequenceEqual(right.Item1))
                return new DiffResult { Error = "Headers differ: left [" + string.Join(", ", lheader) + "] vs right [" + string.Join(", ", right.Item1) + "]" };

            Func<List<Dictionary<string, string>>, string, Dictionary<string, Dictionary<string, string>>> index =
                (recs, label) =>
                {
                    var by = new Dictionary<string, Dictionary<string, string>>();
                    foreach (var rec in recs)
                    {
                        if (by.ContainsKey(rec[key])) throw new InvalidOperationException(label + ": duplicate key \"" + rec[key] + "\"");
                        by[rec[key]] = rec;
                    }
                    return by;
                };
            var leftBy = index(left.Item2, "Left");
            var rightBy = index(right.Item2, "Right");

            var res = new DiffResult();
            // Ordinal order = the TS default sort (UTF-16 code units).
            foreach (var k in leftBy.Keys.Union(rightBy.Keys).OrderBy(x => x, StringComparer.Ordinal))
            {
                Dictionary<string, string> l, r;
                leftBy.TryGetValue(k, out l);
                rightBy.TryGetValue(k, out r);
                if (l == null) res.Rows.Add(new RowDiff { Key = k, Type = "added", After = r });
                else if (r == null) res.Rows.Add(new RowDiff { Key = k, Type = "removed", Before = l });
                else
                {
                    var columns = lheader.Where(n => n != key && l[n] != r[n])
                        .OrderBy(x => x, StringComparer.Ordinal).ToList();
                    if (columns.Count > 0)
                        res.Rows.Add(new RowDiff { Key = k, Type = "changed", Columns = columns, Before = l, After = r });
                }
            }
            res.Same = res.Rows.Count == 0;
            return res;
        }
        catch (InvalidOperationException e)
        {
            return new DiffResult { Error = e.Message };
        }
    }
}

// Example:
// var r = CsvDiff.Diff("id,name\n1,Ada\n2,Bob", "id,name\n1,Ada\n2,Robert\n3,New");
// // r.Rows: [{Key "2", Type "changed", Columns ["name"]}, {Key "3", Type "added"}]
// // r.Same == false
// CsvDiff.Diff("id,name\n1,Ada\n1,Bob", "id,name\n1,Ada").Error
// → "Left: duplicate key \"1\""

Also available in 12 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →