Search code examples
c#splittext-parsing

C# How can I detect a variable contains a comma delimited list of integers?


Is there any simple way to detect if a string variable is set of comma delimited integers, or a single integer?

Here are some examples of variables, and the results I'd expect:

var test1 = "123,456,489";
var test2 = "I, for once, do not know";
var test3 = "123,abc,987";
var test4 = "123";
var test5 = "1234,,134";


Test1 would be true. 
Test2 would be false. It contains alpha characters
Test3 would be falce. It contains alpha characters
Test4 would be true.  It not delimited, but still valid since its an integer.
Test4 would be false.  The second item is null / empty.

I guess I could attack it with a regex, but i wanted to post the question first here in case there are some built-in functionalities in C# that i'm missing.


Solution

  • You could do this:

    int foo;  // Ignored, just required for TryParse()
    bool isListOfInts = testString.Split(',').All(s => int.TryParse(s, out foo));