1

我想测试某个字符串是否包含在一个简短的字符串列表中。目前代码是这样的:

if (new List<string> { "A", "B", "C" }.Contains (str)) {

然而,这似乎臃肿。例如,iirc,在 Java 中我可以简单地编写{"A", "B", "C"}.Contains(str)它,这比上面的要好得多。

我确信在 C# 中有更好的方法。你能指出来吗?

4

5 回答 5

6

我想您可以将其缩短为:

if ((new []{ "A", "B", "C" }).Contains (str)) {

不知道它会产生多大的实际差异。

更新:如果您知道您将只测试一个字母,我认为没有理由制作它的列表或数组:

if ("ABC".Contains(str)) {

该代码既短又快。但话又说回来,我猜单字母字符串只是样本......

于 2009-08-27T08:07:35.427 回答
6

你可以写一个扩展方法:

public static bool In<T>(this T obj, params T[] candidates)
{
    return obj.In((IEnumerable<T>)candidates);
}

public static bool In<T>(this T obj, IEnumerable<T> candidates)
{
    if(obj == null) throw new ArgumentNullException("obj");
    return (candidates ?? Enumerable.Empty<T>()).Contains(obj);
}

然后你可以用它来做:

if(str.In("A", "B", "C")) { ... }
于 2009-08-27T08:53:19.173 回答
2

这种方法怎么样:

"A;B;C".Split(';').Contains(str);
于 2009-08-27T08:09:32.960 回答
2

如果您的短字符串列表是常量,则应使用静态只读字符串数组。

好处是它很容易编写,并且不会在每次需要执行检查时都实例化新的 List。

private static readonly string[] Names = new string[] { "A", "B", "C" };

...

if (Names.Contains(str)) {

但是,此解决方案不可扩展,因为搜索是以线性方式完成的。或者,您可以以排序方式定义常量数组并在数组上使用 BinarySearch。

// this has to be sorted
private static readonly string[] Names = new string[] { "A", "B", "C" };

...

if (Array.BinarySearch(Names, str) >= 0) {
于 2009-08-27T08:22:07.317 回答
2

要彻底改变它:

switch(str){
    case "A":
    case "B":
    case "C":
       contains = true;
       break;

    default:
       contains = false;
       break;
}
于 2009-08-27T08:28:21.190 回答