使用C#进行多个字符串比较

26 浏览
0 Comments

使用C#进行多个字符串比较

假设我需要比较字符串x是否为"A"、"B"或者"C"。

在Python中,我可以使用in运算符来轻松进行检查。

if x in ["A","B","C"]:
    do something

在C#中,我可以这样做:

if (String.Compare(x, "A", StringComparison.OrdinalIgnoreCase) || ...)
    do something

是否有更类似于Python的方法呢?

添加

为了使用不区分大小写的Contain(),我需要添加System.Linq

using System;
using System.Linq;
using System.Collections.Generic;
class Hello {
    public static void Main() {
        var x = "A";
        var strings = new List {"a", "B", "C"};
        if (strings.Contains(x, StringComparer.OrdinalIgnoreCase)) {
            Console.WriteLine("hello");
        }
    }
}

或者

using System;
using System.Linq;
using System.Collections.Generic;
static class Hello {
    public static bool In(this string source, params string[] list)
    {
        if (null == source) throw new ArgumentNullException("source");
        return list.Contains(source, StringComparer.OrdinalIgnoreCase);
    }
    public static void Main() {
        string x = "A";
        if (x.In("a", "B", "C")) {
            Console.WriteLine("hello");
        }
    }
}

0