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" };
If you add an assembly link Microsoft.VisualBasic, you can use the following single-line font:
Microsoft.VisualBasic
bool isEverythingNumeric = str.All(s => Microsoft.VisualBasic.Information.IsNumeric(s));
You can do it:
var isOnlyNumbers = str.All(s => { double i; return double.TryParse(s, out i); });
Try the following:
string[] str = new string[] { "23", "25", "Ho" }; double trouble; if (str.All(number => Double.TryParse(number, out trouble))) { // do stuff }
How to use regular expressions?
using System.Text.RegularExpressions; ... bool isNum= Regex.IsMatch(strToMatch,"^\\d+(\\.\\d+)?$");
TryParse
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)));
Or without linq ...
bool allNumbers = true; foreach(string str in myArray) { int nr; if(!Int32.TryParse(str, out nr)) { allNumbers = false; break; } }