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.
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.
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.
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.
"abc3def".Any(c => char.IsDigit(c));
Update: as @Cipher pointed out, it can actually be made even shorter:
"abc3def".Any(char.IsDigit);
Try this
public static bool HasNumber(this string input) { return input.Where(x => Char.IsDigit(x)).Any(); }
Usage
string x = GetTheString(); if ( x.HasNumber() ) { ... }
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