与C#进行多个字符串比较

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

使用Python,我可以使用运算符来轻松检查。

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 {"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这是IEnumerable上的扩展方法:

 var strings = new List { "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(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 possibleMatches = new List{"A", "B", "C"}; possibleMatches.Contains(inputString); 

当然

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

可能你最好的选择是Select Case(在C#中切换)声明。

编辑:对不起选择案例是VB.NET(我的通常语言),它是在C#切换。

有几种方法,我建议你这样做:

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

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