Split a comma separated string list to a list of integers in C#

Published on Tuesday, 18 February 2014
c#

Today I needed to get a list of UserIds which are stored in the web.config file, separated by commas, in one string.

The below method makes use of Linq to achieve this in a neat solution.

string StringOfUsers = "8,4,5,20,15";
List<int> ListOfUsers = new List<int>();
 
if ((!string.IsNullOrEmpty(StringOfUsers))) {
    ListOfUsers = StringOfUsers.Split(",").Select(s => int.Parse(s)).ToList();
}
 
return ListOfUsers;