假如我需要比较字符串x是否为"A"、"B"或"C"。
使用Python,我可以使用in运算符轻松检查这个条件。
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");
}
}
}