How to Convert a Comma-Separated String into a List of Integers in C#
By FoxLearn 3/6/2025 2:45:19 AM 16
This is a simple task and differs from parsing complex CSV data (with rows of comma-separated values). Here, you can use string.Split(",") to break the string into individual components and then convert each one to an integer.
For example, How to parser a Comma-Separated String into a List of Integers using LINQ in C#
using System.Linq; var csv = "5,10,15"; var ints = csv.Split(",").Select(i => Int32.Parse(i)).ToList(); Console.WriteLine($"We have {ints.Count} ints");
This will output:
We have 3 ints
Although this example demonstrates parsing integers, you can easily modify it to parse any type (such as decimal
, DateTime
, etc.). You can use Convert.ChangeType()
to convert the string into any target type, or use the specific type’s conversion method.
Let’s say you want to parse the comma-separated values and only add valid integers to the list, avoiding errors. You can do this by splitting the string, iterating through the components, and using Int32.TryParse
instead of Int32.Parse
.
List<int> ParseInts(string csv) { var ints = new List<int>(); if (string.IsNullOrEmpty(csv)) return ints; foreach (string s in csv.Split(",")) { if (Int32.TryParse(s, out int i)) ints.Add(i); } return ints; }
You can then use this method to handle different cases:
var first = ParseInts("5,10,15"); Console.WriteLine($"First has {first.Count} valid ints"); var second = ParseInts(""); Console.WriteLine($"Second has {second.Count} valid ints"); var third = ParseInts("5,10,abc,20"); Console.WriteLine($"Third has {third.Count} valid ints");
Output:
First has 3 valid ints Second has 0 valid ints Third has 3 valid ints
Notice that the invalid entry abc
was ignored.
Parsing into a HashSet
If you need to store only unique integers and perform fast lookups, you can use a HashSet
instead of a List
.
To convert the parsed integers into a HashSet
, you can use the LINQ ToHashSet()
method:
using System.Linq; var csv = "5,10,15,5"; var intSet = csv.Split(",").Select(i => Int32.Parse(i)).ToHashSet(); Console.WriteLine($"Set has 5? {intSet.Contains(5)}"); Console.WriteLine($"Set has 100? {intSet.Contains(100)}");
This will output:
Set has 5? True Set has 100? False
In this example, intSet
only contains unique values, and duplicates (like the second "5") are removed.
- How to Get Status Codes with HttpClient in C#
- How to use TimeZoneInfo in C#
- How to Get key with the max value in a dictionary in C#
- How to Get and send JSON with HttpClient in C#
- How to Deserialize JSON as a stream in C#
- How to use JsonNode in C#
- TimeZoneInfo with current UTC offset in C#
- How to Parser a CSV file in C#