Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string has at least one number in it using LINQ

Tags:

c#

linq

I would like to know what the easiest and shortest LINQ query is to return true if a string contains any number character in it.

like image 437
Jobi Joy Avatar asked Oct 08 '09 21:10

Jobi Joy


People also ask

How do you check if a string contains at least one number?

Use the RegExp. test() method to check if a string contains at least one number, e.g. /\d/. test(str) . The test method will return true if the string contains at least one number, otherwise false will be returned.

Can you use Linq on a string?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.

What is any () in Linq?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


2 Answers

"abc3def".Any(c => char.IsDigit(c)); 

Update: as @Cipher pointed out, it can actually be made even shorter:

"abc3def".Any(char.IsDigit); 
like image 168
Fredrik Mörk Avatar answered Sep 23 '22 10:09

Fredrik Mörk


Try this

public static bool HasNumber(this string input) {   return input.Where(x => Char.IsDigit(x)).Any(); } 

Usage

string x = GetTheString(); if ( x.HasNumber() ) {   ... } 
like image 26
JaredPar Avatar answered Sep 21 '22 10:09

JaredPar