在.Net中,"最简洁"的方法来检查字符串是否是多个值中的一个?

Rob*_*b3C 4 .net string

我想检查字符串是否与值列表中的一个匹配.

我当然有很多很多方法可以解决这个问题:if语句,switch语句,RegEx等等.但是,我会认为.Net会有类似的东西.

if (myString.InList("this", "that", "the other thing"))
Run Code Online (Sandbox Code Playgroud)

到目前为止,我能找到的最接近的东西是:

"this; that; the other thing;".Contains(myString)
Run Code Online (Sandbox Code Playgroud)

如果我想在一行中进行检查并且不想使用RegEx,这几乎是唯一的方法吗?

Blu*_*kMN 10

如果你使用的是.NET 3.0,那么有一种类型可枚举对象的方法可以让它在一个内联构造的字符串数组上工作.这对你有用吗?

if ((new string[] { "this", "that", "the other thing" }).Contains(myString))
Run Code Online (Sandbox Code Playgroud)

感谢您的提示评论.确实,这也有效:

if ((new [] { "this", "that", "the other thing" }).Contains(myString))
Run Code Online (Sandbox Code Playgroud)

我一直对使用推断类型是否是一个好主意感到矛盾.简洁是好的,但有时候,当没有明确说明类型时,我会试图找出某些变量的数据类型而感到沮丧.当然,对于这样简单的事情,类型应该是显而易见的.

  • 您甚至可以跳过它的"字符串"部分,因为它可以推断出来. (2认同)
  • 如果你要求它匹配"事物",那么在原始帖子中使用字符串文字的方法会产生误报吗?"thing"出现在列表字符串中,但你不希望它匹配,除非它之前是"另一个"吗? (2认同)

Jos*_*ved 5

您可以使用.NET 3.5中提供的扩展方法来获得类似的语法

if (myString.InList("this", "that", "the other thing")) {}
Run Code Online (Sandbox Code Playgroud)

只需添加这样的东西(并导入它):

public static bool InList(this string text, params string[] listToSearch) {
    foreach (var item in listToSearch) {
        if (string.Compare(item, text, StringComparison.CurrentCulture) == 0) {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是旧版本,您仍然可以使用此功能,但您需要将其称为:

if (InList(myString, "this", "that", "the other thing")) {}
Run Code Online (Sandbox Code Playgroud)

当然,在InList函数中,删除此关键字.