开发者

Easiest way to check numbers

开发者 https://www.devze.com 2022-12-14 02:56 出处:网络
I have a string array. What is开发者_运维知识库 the simplest way to check if all the elements of the array are numbers

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" };


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));


You can do this:

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


Try this:

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


How about using regular expressions?

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

TryParse


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)));


Or without linq...

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号