简体   繁体   中英

Multiple string comparison with C#

Let's say I need to compare if string x is "A", "B", or "C".

With Python, I can use in operator to check this easily.

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

With C#, I can do

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

Can it be something more similar to Python?

ADDED

I needed to add System.Linq in order to use case insensitive 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> :

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.

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:

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.

Edit: Sorry Select Case is VB.NET (my usual language) and it is switch in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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