Friday, 17 March 2017

Check if string contains only numbers c#

            string myString = "354";
         
            var Output= !string.IsNullOrEmpty(myString) && myString.All(char.IsDigit);

             Result => True

        Note=> If you put instated of ALL with Any in above line ,its will return true if                                                 myString contain at least one number . 

         **************** OR Try below******************

                int number;
                bool isNumeric = int.TryParse(myString , out number);
if(isNumeric)
{
// Do your TASK with int n
}

             **************** OR Try With Regex******************
              
                var regex = new Regex(@"^[0-9]+$");
if(regex.IsMatch(myString ))
{
return true;
                       //  Do your TASK

}

No comments:

Post a Comment