TheAlgorithms/C-Sharp · error · ArgumentException

Input lists must have the same length.

Error message

Input lists must have the same length.

What it means

This ArgumentException comes from the argument validation block at the top of LinearRegression.Fit (LinearRegression.cs:42), after the null and empty checks pass. It means the x (independent) and y (dependent) lists describe paired observations, but their counts differ, so pairs cannot be formed to compute means, slope, and intercept. It fires when x.Count != y.Count for otherwise valid non-empty lists.

Solutions

  1. Build x and y from the same records in one pass so lengths always match.
  2. Filter both lists together (by record, not per-series) so invalid rows are dropped from both.
  3. Assert x.Count == y.Count in the caller before calling Fit to get a clearer error.

Example fix

// before
var xs = rows.Select(r => r.X).ToList();
var ys = rows.Where(r => !double.IsNaN(r.Y)).Select(r => r.Y).ToList();
regression.Fit(xs, ys); // length mismatch
// after
var valid = rows.Where(r => !double.IsNaN(r.Y)).ToList();
regression.Fit(valid.Select(r => r.X).ToList(), valid.Select(r => r.Y).ToList());
Defensive patterns

Strategy: validation

Validate before calling

if (xs.Count != ys.Count)
    throw new InvalidOperationException($"x has {xs.Count} values but y has {ys.Count}.");
regression.Fit(xs, ys);

Try / catch

try
{
    regression.Fit(xs, ys);
}
catch (ArgumentException ex) when (ex.Message.Contains("same length"))
{
    // paired series diverged — realign from source records and retry
    (xs, ys) = RebuildPairedSeries(sourceRows);
    regression.Fit(xs, ys);
}

Prevention

When it happens

Trigger: Calling Fit(x, y) where the lists were built independently and one has extra/missing entries — e.g. y built from a filtered subset while x was not.

Common situations: Filtering NaNs out of only one series; separate data sources (one API, one file) with different row counts; an off-by-one when appending samples.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/ea1782db58b5aa35. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/MachineLearning/LinearRegression.cs:42

    /// </summary>
    /// <param name="x">List of independent variable values.</param>
    /// <param name="y">List of dependent variable values.</param>
    /// <exception cref="ArgumentException">Thrown if input lists are null, empty, or of different lengths.</exception>
    public void Fit(IList<double> x, IList<double> y)
    {
        if (x == null || y == null)
        {
            throw new ArgumentException("Input data cannot be null.");
        }

        if (x.Count == 0 || y.Count == 0)
        {
            throw new ArgumentException("Input data cannot be empty.");
        }

        if (x.Count != y.Count)
        {
            throw new ArgumentException("Input lists must have the same length.");
        }

        // Calculate means
        double xMean = x.Average();
        double yMean = y.Average();

        // Calculate slope (b) and intercept (a)
        double numerator = 0.0;
        double denominator = 0.0;
        for (int i = 0; i < x.Count; i++)
        {
            numerator += (x[i] - xMean) * (y[i] - yMean);
            denominator += (x[i] - xMean) * (x[i] - xMean);
        }

        const double epsilon = 1e-12;
        if (Math.Abs(denominator) < epsilon)
        {

View on GitHub (pinned to 96e2905cab)