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

maf*_*afu 1 c# linq string contains list

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

if (new List<string> { "A", "B", "C" }.Contains (str)) {
Run Code Online (Sandbox Code Playgroud)

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

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

Fre*_*örk 6

我想你可以缩短到:

if ((new []{ "A", "B", "C" }).Contains (str)) {
Run Code Online (Sandbox Code Playgroud)

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

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

if ("ABC".Contains(str)) {
Run Code Online (Sandbox Code Playgroud)

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


Lee*_*Lee 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);
}
Run Code Online (Sandbox Code Playgroud)

你可以用它做什么:

if(str.In("A", "B", "C")) { ... }
Run Code Online (Sandbox Code Playgroud)