Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

c# - 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...