假设我需要比较字符串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()。
System.Linq
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"); } } }
使用Enumerable.Contains<T>这是对的扩展方法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 }