简体   繁体   English

与 C# 的多个字符串比较

[英]Multiple string comparison with C#

Let's say I need to compare if string x is "A", "B", or "C".假设我需要比较字符串 x 是“A”、“B”还是“C”。

With Python, I can use in operator to check this easily.使用 Python,我可以使用 in operator 轻松检查它。

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

With C#, I can do有了 C#,我可以做到

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

Can it be something more similar to Python?它可以是更类似于 Python 的东西吗?

ADDED添加

I needed to add System.Linq in order to use case insensitive Contain().我需要添加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");
        }
    }
}

or或者

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

Use Enumerable.Contains<T> which is an extension method on IEnumerable<T> :使用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))

Why yes, there's a classic thread here on StackOverflow with an extension method that would do exactly what you're looking for.为什么是的,StackOverflow 上有一个经典线程,其中包含一个扩展方法,可以完全满足您的需求。

A Use For Extension Methods 扩展方法的使用

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

EDIT in response to comment below: If you are only solely concerned with strings then:编辑以回应以下评论:如果您只关心字符串,则:

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

Which leads to the syntax you're familiar with:这导致您熟悉的语法:

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

Note, this is pretty much exactly the same as everyone else has posted only in a syntax closest to what you mentioned.请注意,这与其他人仅以与您提到的最接近的语法发布的几乎完全相同。

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

Sure当然

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

There are a couple of approaches to this, I would suggest you do something like:有几种方法可以解决这个问题,我建议您执行以下操作:

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

There are a lot of other ways to handle this, and the larger your search field gets, the more likely using an array, hashtable or collection becomes valueable.有很多其他方法可以解决这个问题,搜索字段越大,使用数组、哈希表或集合的可能性就越大。 As long as your field of possibilities remains small, the use of a simple string is going to be your best performance.只要您的可能性范围很小,使用简单的字符串将是您的最佳表现。 All of the overhead of more complex arrays or objects (or arrays of objects...) is unnecessary.更复杂的数组或对象(或对象数组...)的所有开销都是不必要的。

Now that C# 9.0 has pattern matching , there's a new, elegant way to do that:现在 C# 9.0 有pattern matching ,有一个新的,优雅的方式来做到这一点:

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

Or, if you need case-insensitivity:或者,如果您需要不区分大小写:

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

Probably your best bet would be theSelect Case (switch in C#) statement.可能你最好的选择是Select Case(C# 中的 switch)语句。

Edit: Sorry Select Case is VB.NET (my usual language) and it is switch in C#.编辑:抱歉,Select Case 是 VB.NET(我的常用语言),它是 C# 中的 switch。

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

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