与C#进行多个字符串比较

pro*_*eek 23 c# string

假设我需要比较字符串x是"A","B"还是"C".

使用Python,我可以使用运算符来轻松检查.

if x in ["A","B","C"]:
    do something
Run Code Online (Sandbox Code Playgroud)

使用C#,我可以做到

if (String.Compare(x, "A", StringComparison.OrdinalIgnoreCase) || ...)
    do something
Run Code Online (Sandbox Code Playgroud)

它可以与Python更相似吗?

添加

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

using System;
using System.Linq;
using System.Collections.Generic;

class Hello {
    public static void Main() {
        var x = "A";

        var strings = new List<string> {"a", "B", "C"};
        if (strings.Contains(x, StringComparer.OrdinalIgnoreCase)) {
            Console.WriteLine("hello");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

jas*_*son 30

使用Enumerable.Contains<T>这是一种扩展方法IEnumerable<T>:

var strings = new List<string> { "A", "B", "C" };
string x = // some string
bool contains = strings.Contains(x, StringComparer.OrdinalIgnoreCase);
if(contains) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)


adr*_*anm 24

if ((new[]{"A","B","C"}).Contains(x, StringComparer.OrdinalIgnoreCase))
Run Code Online (Sandbox Code Playgroud)


Khe*_*pri 10

为什么是这样,StackOverflow上有一个经典的线程,它带有一个扩展方法,可以完全满足您的需求.

用于扩展方法

public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}
Run Code Online (Sandbox Code Playgroud)

编辑以回应下面的评论:如果您只关注字符串,那么:

public static bool In(this string source, params string[] list)
{
    if (null == source) throw new ArgumentNullException("source");
    return list.Contains(source, StringComparer.OrdinalIgnoreCase);
}
Run Code Online (Sandbox Code Playgroud)

这导致您熟悉的语法:

if(x.In("A","B","C"))
{
  // do something....
}
Run Code Online (Sandbox Code Playgroud)

请注意,这几乎与其他人仅使用最接近您提到的语法发布的内容完全相同.