prosseek prosseek -3 years ago 102
C# Question

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

Answer Source

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
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download