有没有更好的方法来编写新的List <string> {“a”,“b”}。包含(str)?</string>

时间:2009-08-27 08:00:21

标签: c# linq string list contains

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

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

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

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

5 个答案:

答案 0 :(得分:6)

我想你可以缩短为:

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

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

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

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

该代码更短更快。但话说再说一遍,我认为单字母字符串只是样本......

答案 1 :(得分: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")) { ... }

答案 2 :(得分:2)

这种方法怎么样:

"A;B;C".Split(';').Contains(str);

答案 3 :(得分: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) {

答案 4 :(得分:2)

完全改变它:

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

    default:
       contains = false;
       break;
}