检查字符串是否包含下划线以外的非字母数字

Check if string contains non-alphanumeric except underscore

我正在尝试编写 if 语句,如果字符串包含除下划线以外的任何非字母数字字符,该语句将运行。

这就是我所拥有的,我正在尝试寻找一种简单的方法来为下划线添加例外,但我遇到了困难。 (其中键是一个字符串)。

// Check for non-alphanumerics except underscore
if (!(key.All(char.IsLetterOrDigit)))                                        
{
    validationResult = false;
}

您只需要扩展 All:

中的逻辑
if (!(key.All(c => char.IsLetterOrDigit(c) || c=='_')))