tags:

views:

235

answers:

6

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" };
+4  A: 

Try this:

string[] str = new string[] { "23", "25", "Ho" };
double trouble;
if (str.All(number => Double.TryParse(number, out trouble)))
{
    // do stuff
}
Rubens Farias
Nice idea, but this will work only if all the numbers fit inside an Int32.
Konamiman
In which case, double.TryParse should work.
Coder 42
+2  A: 

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)));
Konamiman
But this will not work with strings that contains white space. And how about scientific notation?
Mark Seemann
seems we need to define what's a number first =)
Rubens Farias
Kona ... what about -1? That's not a downvote :P Just a question ;)
Daniel Elliott
That won't work with decimal points.
Coder 42
And what about decimal points?
Mark Seemann
Well, that would work with the example provided. Maybe the asker could clarify if he needs to check for non-digit characters?
Konamiman
+6  A: 

You can do this:

var isOnlyNumbers = str.All(s =>
    {
        double i;
        return double.TryParse(s, out i);
    });
Mark Seemann
Why the anonymous downvote?
Mark Seemann
+6  A: 

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));
Heinzi
Clever +1 ... out-of-the-box thinking
Daniel Elliott
+1, this idea scares me, but, hell, it works =)
Rubens Farias
Why use something that seems so specific to VisualBasic?
dfowler
Good thinking, however, I don't know if it is worth for the use of 1 function including an entire dll.
James
Why is something so generally useful in the VisualBasic assembly? (also see http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx)
Coder 42
+1  A: 

Or without linq...

bool allNumbers = true;
foreach(string str in myArray)
{
   int nr;
   if(!Int32.TryParse(str, out nr))
   {
      allNumbers = false;
      break;
   }
}
Carra
Why not using linq? You may continue with writing your own TryParse method:)
Kamarey
Because our evil boss forces us to use C# 2.0 ;)
Carra
+3  A: 

How about using regular expressions?

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

TryParse

PRR