C#
programming
data-conversion
lists
string-manipulation

How can I convert comma separated string into a Listint

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Converting a comma-separated string like "1,2,3,4,5" into a List<int> in C# is a common task when processing CSV data, query parameters, user input, or configuration values. The standard approach uses string.Split() to separate the values and LINQ's Select(int.Parse) to convert each substring to an integer. For production code, handling whitespace, empty entries, and invalid values is essential to avoid runtime exceptions.

Basic Conversion with LINQ

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5string input = "1,2,3,4,5";
6
7List<int> numbers = input.Split(',')
8                         .Select(int.Parse)
9                         .ToList();
10
11Console.WriteLine(string.Join(", ", numbers));  // 1, 2, 3, 4, 5

Split(',') produces a string[] of substrings. Select(int.Parse) converts each string to an int. ToList() materializes the result into a List<int>.

Handling Whitespace

csharp
1// Input with spaces around values
2string input = " 1 , 2 , 3 , 4 , 5 ";
3
4// Option 1: Trim each element
5List<int> numbers = input.Split(',')
6                         .Select(s => int.Parse(s.Trim()))
7                         .ToList();
8
9// Option 2: Split with StringSplitOptions and trim
10List<int> numbers2 = input.Split(',', StringSplitOptions.TrimEntries)
11                          .Select(int.Parse)
12                          .ToList();
13// StringSplitOptions.TrimEntries requires .NET 5+

User input and CSV data often include spaces around commas. Without trimming, int.Parse(" 2 ") succeeds (it ignores whitespace), but it is cleaner to trim explicitly.

Handling Empty and Invalid Entries

csharp
1// Input with empty entries and trailing commas
2string input = "1,,2,abc,3,,4";
3
4// Remove empty entries
5List<int> clean = input.Split(',', StringSplitOptions.RemoveEmptyEntries)
6                       .Select(s => s.Trim())
7                       .Where(s => int.TryParse(s, out _))
8                       .Select(int.Parse)
9                       .ToList();
10
11Console.WriteLine(string.Join(", ", clean));  // 1, 2, 3, 4
12
13// Alternative: TryParse with a helper
14List<int> safe = input.Split(',')
15                      .Select(s => { int.TryParse(s.Trim(), out int val); return (ok: int.TryParse(s.Trim(), out val), val); })
16                      .Where(x => x.ok)
17                      .Select(x => x.val)
18                      .ToList();

StringSplitOptions.RemoveEmptyEntries handles consecutive commas and trailing commas. Filtering with int.TryParse silently skips non-numeric values instead of throwing a FormatException.

Using Array.ConvertAll (No LINQ)

csharp
1string input = "10,20,30,40,50";
2
3// Without LINQ — uses Array.ConvertAll
4int[] array = Array.ConvertAll(input.Split(','), int.Parse);
5List<int> numbers = new List<int>(array);
6
7Console.WriteLine(numbers.Count);  // 5

Array.ConvertAll is a concise alternative when LINQ is not needed. It converts each element using the specified converter function and returns an array.

Parsing to Other Numeric Types

csharp
1string floatInput = "1.5,2.7,3.14,4.0";
2string longInput = "100000000,200000000,300000000";
3
4// Parse to List<double>
5List<double> doubles = floatInput.Split(',')
6                                 .Select(double.Parse)
7                                 .ToList();
8
9// Parse to List<long>
10List<long> longs = longInput.Split(',')
11                            .Select(long.Parse)
12                            .ToList();
13
14// Parse with specific culture (for decimal comma locales)
15using System.Globalization;
16List<double> invariant = floatInput.Split(',')
17    .Select(s => double.Parse(s, CultureInfo.InvariantCulture))
18    .ToList();

Converting Back to a Comma-Separated String

csharp
1List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
2
3// Using string.Join
4string csv = string.Join(",", numbers);
5Console.WriteLine(csv);  // "1,2,3,4,5"
6
7// With formatting
8string formatted = string.Join(", ", numbers.Select(n => n.ToString("D3")));
9Console.WriteLine(formatted);  // "001, 002, 003, 004, 005"

Complete Robust Parser

csharp
1public static class CsvParser
2{
3    public static List<int> ParseIntList(string input, char separator = ',')
4    {
5        if (string.IsNullOrWhiteSpace(input))
6            return new List<int>();
7
8        var results = new List<int>();
9        foreach (string part in input.Split(separator))
10        {
11            string trimmed = part.Trim();
12            if (int.TryParse(trimmed, out int value))
13            {
14                results.Add(value);
15            }
16            // Silently skip invalid entries
17        }
18        return results;
19    }
20}
21
22// Usage
23List<int> nums = CsvParser.ParseIntList("1, 2, abc, 3, , 4");
24Console.WriteLine(string.Join(", ", nums));  // 1, 2, 3, 4
25
26List<int> empty = CsvParser.ParseIntList("");
27Console.WriteLine(empty.Count);  // 0
28
29List<int> semicolons = CsvParser.ParseIntList("1;2;3", ';');
30Console.WriteLine(string.Join(", ", semicolons));  // 1, 2, 3

Common Pitfalls

  • Using int.Parse on untrusted input: int.Parse throws FormatException for non-numeric strings and OverflowException for values outside int range. Use int.TryParse to safely handle invalid input without exceptions.
  • Forgetting to handle empty strings from Split: "1,,3".Split(',') produces ["1", "", "3"]. Parsing the empty string throws FormatException. Use StringSplitOptions.RemoveEmptyEntries or filter out empty strings before parsing.
  • Culture-dependent decimal parsing: double.Parse("3.14") fails in locales where the decimal separator is a comma (e.g., German, French). Use CultureInfo.InvariantCulture when parsing numbers from machine-generated strings like CSV files or API responses.
  • Calling ToList() multiple times in a chain: Each ToList() allocates a new list. Chain LINQ operations and call ToList() only at the end. input.Split(',').ToList().Select(int.Parse).ToList() creates two lists when one suffices.
  • Not trimming whitespace before parsing: " 1 , 2 , 3 " with Split(',') produces [" 1 ", " 2 ", " 3 "]. While int.Parse tolerates leading/trailing whitespace, double.Parse with specific cultures may not. Always trim for consistency.

Summary

  • Use input.Split(',').Select(int.Parse).ToList() for basic conversion
  • Add StringSplitOptions.RemoveEmptyEntries to handle empty entries
  • Use int.TryParse to safely skip non-numeric values
  • Trim whitespace with .Select(s => s.Trim()) or StringSplitOptions.TrimEntries (.NET 5+)
  • Use CultureInfo.InvariantCulture for locale-independent parsing
  • Convert back with string.Join(",", list)

Course illustration
Course illustration

All Rights Reserved.