Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Split a string of integers into an IEnumerable<int>

Tags:

syntax

c#

parsing

I need to convert a string of comma separated integers into a list of integers.

What is the best way to do this?

I can do it below but am worried about the performance - Is there a better more efficient way to do this?

public IEnumerable<int> GetListOfIds()
{
    string Ids = "1,4,5,7,12"; // would be passed into method
    List<int> _result = Ids.Split(',')
                           .ToList()
                           .Select(item => int.Parse(item))
                           .ToList();

    return _result;
}
like image 441
Noel Avatar asked Oct 11 '11 18:10

Noel


2 Answers

There's no need to call ToList, but otherwise your code looks fine:

public IEnumerable<int> GetListOfIds(string ids)
{
    return ids.Split(',').Select(item => int.Parse(item));
}

You may also want to consider adding error handling in case the input string is invalid:

public IEnumerable<int> GetListOfIds(string ids)
{
    foreach (string part in ids.Split(','))
    {
        int x;
        if (!int.TryParse(part, out x))
        {
            throw new ArgumentException(
                string.Format("The value {0} cannot be parsed as an integer.", part),
                "ids");
        }
        else
        {
            yield return x;
        }
    }
}
like image 190
Mark Byers Avatar answered Sep 16 '22 13:09

Mark Byers


You may at least omit first ToList() statement - so it will be

  List<int> _result = Ids.Split(',').Select(item => int.Parse(item)).ToList();
like image 22
Sergey Kudriavtsev Avatar answered Sep 20 '22 13:09

Sergey Kudriavtsev