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
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
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
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)
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
Converting Back to a Comma-Separated String
Complete Robust Parser
Common Pitfalls
- Using
int.Parseon untrusted input:int.ParsethrowsFormatExceptionfor non-numeric strings andOverflowExceptionfor values outsideintrange. Useint.TryParseto safely handle invalid input without exceptions. - Forgetting to handle empty strings from
Split:"1,,3".Split(',')produces["1", "", "3"]. Parsing the empty string throwsFormatException. UseStringSplitOptions.RemoveEmptyEntriesor 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). UseCultureInfo.InvariantCulturewhen parsing numbers from machine-generated strings like CSV files or API responses. - Calling
ToList()multiple times in a chain: EachToList()allocates a new list. Chain LINQ operations and callToList()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 "withSplit(',')produces[" 1 ", " 2 ", " 3 "]. Whileint.Parsetolerates leading/trailing whitespace,double.Parsewith specific cultures may not. Always trim for consistency.
Summary
- Use
input.Split(',').Select(int.Parse).ToList()for basic conversion - Add
StringSplitOptions.RemoveEmptyEntriesto handle empty entries - Use
int.TryParseto safely skip non-numeric values - Trim whitespace with
.Select(s => s.Trim())orStringSplitOptions.TrimEntries(.NET 5+) - Use
CultureInfo.InvariantCulturefor locale-independent parsing - Convert back with
string.Join(",", list)

