假设我需要比较字符串 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");
}
}
}
最佳答案
使用 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
}
关于c# - 使用 C# 进行多字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6034503/