4

尝试使用 LINQ 重写它:

if (mode != "A" && mode != "B" && mode != "C" && mode != "D" && mode != "E" && mode != "F" && mode != "G")
{
   continue;
}

重构这个最清晰和简洁的方法是什么?我可以发誓我以前看过这样的帖子,但我现在找不到。

4

5 回答 5

10

您可以使用以下Contains方法IList<T>

IList<string> modes = new[]{"A","B","C","D","E","F","G"};
if (!modes.Contains(mode))...
于 2012-11-02T15:21:54.907 回答
2

为字符串类编写扩展方法

public static bool In(this string s, params string[] values)
{
    return values.Any(x => x.Equals(s));
}

这样称呼

if (!mode.In("A", "B", "C", "D","E","F", "G")
{
    continue;
}
于 2012-11-02T15:22:42.993 回答
1
var modes = new[] { "A","B","C","D","E","F","G"};

if (modes.All(a => mode != a)) 
    continue;
于 2012-11-02T15:21:42.320 回答
1

我一直使用这种扩展方法

public static bool IsIn(this string source, params string[] parms)
{
    return parms.Contains(source);
}

并按如下方式使用它:

if (!mode.IsIn("A", "B", "C", "D", "E", "F", "G"))
{
    continue;
}

下一步,如果你经常使用它,是

public static bool IsNotIn(this string source, params string[] parms)
{
    return !IsIn(source, params);
}

你会变得更易读

if (mode.IsNotIn("A", "B", "C", "D", "E", "F", "G"))
{
    continue;
}
于 2012-11-02T15:24:29.220 回答
1
string s = "ABCDEFG";
bool res = s.Any(item => { return (int)item > 64 && (int)item < 72; });
于 2012-11-02T15:28:38.147 回答