C# 如何检测包含逗号分隔的整数列表的变量?

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

是否有任何简单的方法来检测字符串变量是逗号分隔的整数集还是单个整数?

这里有一些变量示例,以及我期望的结果:

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.

我想我可以用正则表达式攻击它,但我想先post这里的问题,以防 C# 中缺少一些内置功能。

你可以这样做:

int foo;  // Ignored, just required for TryParse()
bool isListOfInts = testString.Split(',').All(s => int.TryParse(s, out foo));
int outInt;
bool isListOfInts = !variablename.Split(",").Any(x=>!int.TryParse(x, outInt));

这是一个正则表达式示例:

string pattern = @"^\d+(,\d+)*$";
string input = "123,456,489";
bool isMatch = Regex.IsMatch(input, pattern);