tags:

views:

177

answers:

2

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.

Thanks Jobi Joy

+4  A: 

Try this

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

Usage

string x = GetTheString();
if ( x.HasNumber() ) {
  ...
}
JaredPar
Or simply `input.Any(x => Char.IsDigit(x));`
Mehrdad Afshari
@Mehrdad, yeah I constantly forget about that overload
JaredPar
+12  A: 
"abc3def".Any(c => char.IsDigit(c));

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

"abc3def".Any(char.IsDigit);
Fredrik Mörk
`.ToCharArray()` is not necessary. `System.String` implements `IEnumerable<char>`.
Mehrdad Afshari
@Mehrdad: Thanks for pointing that out; I tend to forget that string implements that interface
Fredrik Mörk
+1, I constantly forget about that particular overload of Any
JaredPar
you could also use char.IsDigit as a method group. .Any(char.IsDigit)
Cipher
@Cipher: true, it does fit the signature.
Fredrik Mörk