Самый легкий путь к контрольным числам

У меня есть массив строк. Что является самым простым способом проверить, являются ли все элементы массива числами

string[] str = new string[] { "23", "25", "Ho" };
5
задан ScG 14 December 2009 в 09:22
поделиться

6 ответов

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));
6
ответ дан 18 December 2019 в 07:09
поделиться

You can do this:

var isOnlyNumbers = str.All(s =>
    {
        double i;
        return double.TryParse(s, out i);
    });
6
ответ дан 18 December 2019 в 07:09
поделиться

How about using regular expressions?

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

TryParse

3
ответ дан 18 December 2019 в 07:09
поделиться

Try this:

string[] str = new string[] { "23", "25", "Ho" };
double trouble;
if (str.All(number => Double.TryParse(number, out trouble)))
{
    // do stuff
}
4
ответ дан 18 December 2019 в 07:09
поделиться

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)));
2
ответ дан 18 December 2019 в 07:09
поделиться

Or without linq...

bool allNumbers = true;
foreach(string str in myArray)
{
   int nr;
   if(!Int32.TryParse(str, out nr))
   {
      allNumbers = false;
      break;
   }
}
1
ответ дан 18 December 2019 в 07:09
поделиться
Другие вопросы по тегам:

Похожие вопросы: