The easiest way to check the numbers

I have a string array. What is the easiest way to check if all elements of an array are numbers

string[] str = new string[] { "23", "25", "Ho" };
+5
source share
6 answers

If you add an assembly link Microsoft.VisualBasic, you can use the following single-line font:

bool isEverythingNumeric = 
    str.All(s => Microsoft.VisualBasic.Information.IsNumeric(s));
+6
source

You can do it:

var isOnlyNumbers = str.All(s =>
    {
        double i;
        return double.TryParse(s, out i);
    });
+6
source

Try the following:

string[] str = new string[] { "23", "25", "Ho" };
double trouble;
if (str.All(number => Double.TryParse(number, out trouble)))
{
    // do stuff
}
+4
source

How to use regular expressions?

 using System.Text.RegularExpressions;
 ...
 bool isNum= Regex.IsMatch(strToMatch,"^\\d+(\\.\\d+)?$");

TryParse

+3
source

Using the fact that the string is also an array of characters, you can do something like this:

str.All(s => s.All(c => Char.IsDigit(c)));
+2
source

Or without linq ...

bool allNumbers = true;
foreach(string str in myArray)
{
   int nr;
   if(!Int32.TryParse(str, out nr))
   {
      allNumbers = false;
      break;
   }
}
+1
source

All Articles