{"record":{"id":"ea1782db58b5aa35","repo":"TheAlgorithms/C-Sharp","slug":"input-lists-must-have-the-same-length","errorCode":null,"errorMessage":"Input lists must have the same length.","messagePattern":"Input lists must have the same length\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/MachineLearning/LinearRegression.cs","lineNumber":42,"sourceCode":"    /// </summary>\n    /// <param name=\"x\">List of independent variable values.</param>\n    /// <param name=\"y\">List of dependent variable values.</param>\n    /// <exception cref=\"ArgumentException\">Thrown if input lists are null, empty, or of different lengths.</exception>\n    public void Fit(IList<double> x, IList<double> y)\n    {\n        if (x == null || y == null)\n        {\n            throw new ArgumentException(\"Input data cannot be null.\");\n        }\n\n        if (x.Count == 0 || y.Count == 0)\n        {\n            throw new ArgumentException(\"Input data cannot be empty.\");\n        }\n\n        if (x.Count != y.Count)\n        {\n            throw new ArgumentException(\"Input lists must have the same length.\");\n        }\n\n        // Calculate means\n        double xMean = x.Average();\n        double yMean = y.Average();\n\n        // Calculate slope (b) and intercept (a)\n        double numerator = 0.0;\n        double denominator = 0.0;\n        for (int i = 0; i < x.Count; i++)\n        {\n            numerator += (x[i] - xMean) * (y[i] - yMean);\n            denominator += (x[i] - xMean) * (x[i] - xMean);\n        }\n\n        const double epsilon = 1e-12;\n        if (Math.Abs(denominator) < epsilon)\n        {","sourceCodeStart":24,"sourceCodeEnd":60,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/MachineLearning/LinearRegression.cs#L24-L60","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Build x and y from the same records in one pass so lengths always match.","Filter both lists together (by record, not per-series) so invalid rows are dropped from both.","Assert x.Count == y.Count in the caller before calling Fit to get a clearer error."],"exampleFix":"// before\nvar xs = rows.Select(r => r.X).ToList();\nvar ys = rows.Where(r => !double.IsNaN(r.Y)).Select(r => r.Y).ToList();\nregression.Fit(xs, ys); // length mismatch\n// after\nvar valid = rows.Where(r => !double.IsNaN(r.Y)).ToList();\nregression.Fit(valid.Select(r => r.X).ToList(), valid.Select(r => r.Y).ToList());","handlingStrategy":"validation","validationCode":"if (xs.Count != ys.Count)\n    throw new InvalidOperationException($\"x has {xs.Count} values but y has {ys.Count}.\");\nregression.Fit(xs, ys);","typeGuard":null,"tryCatchPattern":"try\n{\n    regression.Fit(xs, ys);\n}\ncatch (ArgumentException ex) when (ex.Message.Contains(\"same length\"))\n{\n    // paired series diverged — realign from source records and retry\n    (xs, ys) = RebuildPairedSeries(sourceRows);\n    regression.Fit(xs, ys);\n}","preventionTips":["Always derive x and y from the same collection of records in a single pass.","Drop invalid records entirely (both x and y) rather than filtering one series.","Assert paired lengths in unit tests for the data-preparation code."],"tags":["csharp","length-mismatch","machine-learning","linear-regression"],"backgroundTag":"shape-mismatch","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}