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;
}
}
精彩评论