繁体   English   中英

与 C# 的多个字符串比较

[英]Multiple string comparison with C#

假设我需要比较字符串 x 是“A”、“B”还是“C”。

使用 Python,我可以使用 in operator 轻松检查它。

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
}
if ((new[]{"A","B","C"}).Contains(x, StringComparer.OrdinalIgnoreCase))

为什么是的,StackOverflow 上有一个经典线程,其中包含一个扩展方法,可以完全满足您的需求。

扩展方法的使用

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

编辑以回应以下评论:如果您只关心字符串,则:

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

这导致您熟悉的语法:

if(x.In("A","B","C"))
{
  // do something....
}

请注意,这与其他人仅以与您提到的最接近的语法发布的几乎完全相同。

List<string> possibleMatches = new List<string>{"A", "B", "C"};
if (possibleMatches.Contains(inputString))
{
  // do something
}

当然

var lst = new List<string>() { "A", "B", "C" };
if (lst.Contains(x, StringComparer.OrdinalIgnoreCase) {
   // do something
}

有几种方法可以解决这个问题,我建议您执行以下操作:

 private const string _searched = "A|B|C|";
 private void button1_Click(object sender, EventArgs e)
 {
     string search = "B" + "|";
     if (_searched.IndexOf(search) > -1)
     {
         //do something
     }
 }

有很多其他方法可以解决这个问题,搜索字段越大,使用数组、哈希表或集合的可能性就越大。 只要您的可能性范围很小,使用简单的字符串将是您的最佳表现。 更复杂的数组或对象(或对象数组...)的所有开销都是不必要的。

现在 C# 9.0 有pattern matching ,有一个新的,优雅的方式来做到这一点:

if (x is "A" or "B" or "C") { ... }

或者,如果您需要不区分大小写:

if (x.ToUpperInvariant() is "A" or "B" or "C") { ... }

可能你最好的选择是Select Case(C# 中的 switch)语句。

编辑:抱歉,Select Case 是 VB.NET(我的常用语言),它是 C# 中的 switch。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM