簡體   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