I have a string array. What is the simplest way to check if all the elements of the array are numbers
string[] str = new string[] { "23", "25", "Ho" };
I have a string array. What is the simplest way to check if all the elements of the array are numbers
string[] str = new string[] { "23", "25", "Ho" };
Try this:
string[] str = new string[] { "23", "25", "Ho" };
double trouble;
if (str.All(number => Double.TryParse(number, out trouble)))
{
// do stuff
}
Using the fact that a string is also an array of chars, you could do something like this:
str.All(s => s.All(c => Char.IsDigit(c)));
You can do this:
var isOnlyNumbers = str.All(s =>
{
double i;
return double.TryParse(s, out i);
});
If you add a reference to the Microsoft.VisualBasic
assembly, you can use the following one-liner:
bool isEverythingNumeric =
str.All(s => Microsoft.VisualBasic.Information.IsNumeric(s));
Or without linq...
bool allNumbers = true;
foreach(string str in myArray)
{
int nr;
if(!Int32.TryParse(str, out nr))
{
allNumbers = false;
break;
}
}