C# – Parse a comma-separated string into a list of integers

Let’s say you want to parse a comma-separated string into a list of integers. For example, you have “1,2,3” and you want to parse it into [1,2,3]. This is different from parsing CSV with rows of comma-separated values. This is more straightforward. You can use string.Split(“,”) to get the individual values and then convert them to the target type (int in this case).

If you don’t need to guard against invalid data, you can do this with a Linq one-liner:

using System.Linq; var csv = "1,2,3"; var ints = csv.Split(",").Select(i => Int32.Parse(i)).ToList(); Console.WriteLine($"We have {ints.Count} ints");
Code language: C# (cs)

This outputs:

We have 3 ints

Even though this example is specifically showing how to parse comma-separated integers, you can do the same approach for any target type (decimal, DateTime, etc…).

Guard against invalid data

The one-liner approach with Linq will fail if there’s invalid data (like if it doesn’t contain valid integers).

Let’s say you want to parse the comma-separated integers and only add valid ones to the list. You can do that by splitting the string, looping through the individual values, and using Int32.TryParse (instead of Int.Parse()). Here’s a method that does this:

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; }
Code language: C# (cs)

Here’s an example of using this method on various inputs (valid and invalid):

var first = ParseInts("1,2,3"); Console.WriteLine($"First has {first.Count} valid ints"); var second = ParseInts(""); Console.WriteLine($"Second has {second.Count} valid ints"); var third = ParseInts("1,2,c,4d"); Console.WriteLine($"Third has {third.Count} valid ints");
Code language: C# (cs)

This outputs the following:

First has 3 valid ints Second has 0 valid ints Third has 2 valid ints

Parsing into a HashSet

If you want a HashSet instead of a List (to only keep unique values and for efficient lookup), use the Linq ToHashSet() method, like this:

using System.Linq; var csv = "1,2,3"; var intSet = csv.Split(",").Select(i => Int32.Parse(i)).ToHashSet(); Console.WriteLine($"Set has 1? {intSet.Contains(1)}"); Console.WriteLine($"Set has 200? {intSet.Contains(200)}");
Code language: C# (cs)

This outputs the following:

Set has 1? True Set has 200? False
Code language: plaintext (plaintext)

Leave a Comment