Chuỗi test: string str = "3456";
Dùng LINQ All với char.IsDigit:
bool isNumber = str.All(c => char.IsDigit(c));
Ví dụ hoàn chỉnh
using System;
using System.Linq;
namespace Demo
{
public class MyApplication
{
public static void Main(string[] args)
{
string str = "3456";
Console.WriteLine(str.All(c => char.IsDigit(c)));
}
}
}
Kết quả
True
Các cách khác:
int.TryParse(str, out _)- chuẩn, xử lý sign, overflowlong.TryParse,double.TryParsecho kiểu khácRegex.IsMatch(str, @"^\d+$")- chỉ digitstr.All(char.IsDigit)- method group syntax
Lưu ý: char.IsDigit chấp nhận Unicode digit (ví dụ: ١٢٣ Arabic-Indic). int.TryParse chỉ nhận ASCII 0-9 trừ khi dùng NumberStyles.