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.
How about
values.All(s => s.All(Char.IsDigit));
That checks that for all strings in the sequence all characters are digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With