Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all strings in a string array are all digits?

Tags:

c#

linq

I have a string, and I want it to be only digits. I tried this, using LINQ:

string[] values = { "123", "a123" };
bool allStringsContaintsOnlyDigits = true;

foreach(string value in values)
{
    if(!value.All(char.IsDigit))
    {
        allStringsContaintsOnlyDigits = false;
        break;
    }
}

if(allStringsContaintsOnlyDigits) { /* Do Stuff */ }

But a loop for only two strings (and it is guaranteed that I have two strings) is a bit tedious...

So I thought maybe doing this:

if(values[0].All(char.isDigit) && values[1].All(char.isDigit)) { /* Do Stuff */ }

But is there a more elegant way? Something like:

values.All(char.IsDigit) // for all strings

Thanks.

Note: negative numbers need to be rejected. Meaning: -125 should return false.

like image 601
Michael Haddad Avatar asked Dec 18 '25 07:12

Michael Haddad


1 Answers

How about

values.All(s => s.All(Char.IsDigit));

That checks that for all strings in the sequence all characters are digits.

like image 109
René Vogt Avatar answered Dec 20 '25 19:12

René Vogt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!