Question

I create calculator which have buttons with numbers and operators for basic operation (+, -,...) and just want to filter buttons with numbers to detect when is clicked number (between 0-9). Also i put new eventhadler which convert sender to button.

I wondering what will be nice and easy way to filter the buttons with numbers (using linq) What did i try so far is

if(btn.Text == btn.Text.Contains(x => x >= '0' && x <= '9')) 
    MessageBox.Show("number " + btn.Text + " is pressed!");

How to make upper code workable?

Was it helpful?

Solution 2

If all you want to know is that is it a number or not do this. No LINQ is required

LINQ Way to check the numbers are between 0 and 9

if(yourstring.ToCharArray().Where(c=> c < '0' || c > '9').Any())
  return false;
else
 return true;

To check that it contains a valid number

double num;
if (double.TryParse(btn.Text, out num))
{
    // It's a number!
}

or to check less than 10 without linq

static bool IsLessThanTen(string str)
{
    foreach (char c in str)
    {
        if (c < '0' || c > '9')
            return false;
    }

    return true;
}

OTHER TIPS

Here you go, for your immediate needs:

if(btn.Text.All(char.IsDigit))
{
    //Do your stuff
}

if you need to check at least one number in the button text, then use below

return btn.Text.Any(char.IsDigit)

If you writing calculator, you better check NCalc - Mathematical Expressions Evaluator for .NET and this CodeProject tutorial

This should work

bool hasNumeric = yourString.IndexOfAny("0123456789".ToCharArray()) > -1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top