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

标签 c# string

假设我需要比较字符串 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 一些?

已添加

我需要添加 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");
        }
    }
}

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");
        }
    }
}

最佳答案

使用 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
}

关于c# - 使用 C# 进行多字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6034503/

相关文章:

c - 纯 C 字符串替换整个单词

c - 如何摆脱 C 中的 "call is the same expression as the source"警告?

c# - 是否可以使用 C# 在 excel 工作簿中编写功能

c# - 如何使用 Mock.Of<T>() 模拟没有默认构造函数的类?

c# - 表单焦点问题

c - 将数组中的元素添加到结构体数组

java - 数组的赋值

c - 如何让 fgets() 在开头忽略 a\n?

c# - 找到具有给定圆心、半径和度数的圆上的点

c# - Linq xml 到对象 - 如何填充集合<foo>