Max Max - 1 month ago 9
C# Question

Convert comma separated string of ints to int array

I only found a way to do it the opposite way round: create a comma separated string from an int list or array, but not on how to convert input like

string str = "1,2,3,4,5";
to an array or list of ints.

Here is my implementation (inspired by this post by Eric Lippert):

public static IEnumerable<int> StringToIntList(string str)
{
if (String.IsNullOrEmpty(str))
{
yield break;
}

var chunks = str.Split(',').AsEnumerable();

using (var rator = chunks.GetEnumerator())
{
while (rator.MoveNext())
{
int i = 0;

if (Int32.TryParse(rator.Current, out i))
{
yield return i;
}
else
{
continue;
}
}
}
}


Do you think this is a good approach or is there a more easy, maybe even built in way?

EDIT: Sorry for any confusion, but the method needs to handle invalid input like
"1,2,,,3"
or
"###, 5,"
etc. by skipping it.

Answer

You should use a foreach loop, like this:

public static IEnumerable<int> StringToIntList(string str) {
    if (String.IsNullOrEmpty(str))
        yield break;

    foreach(var s in str.Split(',')) {
        int num;
        if (int.TryParse(s, out num))
            yield return num;
    }
}

Note that like your original post, this will ignore numbers that couldn't be parsed.

If you want to throw an exception if a number couldn't be parsed, you can do it much more simply using LINQ:

return (str ?? "").Split(',').Select<string, int>(int.Parse);
Comments