0

我有以下方法:

public static List<string> GetArgsListStartsWith(string filter, bool invertSelection, bool lowercaseArgs)
{
    return GetArgumentsList(lowercaseArgs)
          .Where(x => !invertSelection && x.StartsWith(filter)).ToList();
}

然后我这样称呼它GetArgsListStartsWith("/", true, false)

这将转化为:获取所有不以“/”开头的参数的列表。问题是列表没有被填充,即使所有参数都不以“/”开头。

如果我调用GetArgsListStartsWith("/", false, false)which 转换为:获取以“/”开头的所有参数的列表,该列表确实会填充以“/”开头的参数。

我怀疑设置为true并返回false时!invertSelection && x.StartsWith(filter)不会返回,但我不明白为什么。有人看到我看不到的东西吗?trueinvertSelectionx.StartsWith(filter)

4

3 回答 3

9

正如其他答案所说,您的条件只有在为假时才会返回真。invertSelection

有条件地反转结果的最简单方法是使用XOR 运算符

.Where(x => x.StartsWith(filter) ^ invertSelection)

我更喜欢这个而不是 lc 的解决方案,因为它只指定StartsWith一次。

于 2012-08-14T09:49:20.947 回答
7
.Where(x => invertSelection ? !x.StartsWith(filter) : x.StartsWith(filter))
于 2012-08-14T09:47:23.253 回答
2

!invertSelection && x.StartsWith(filter) 其中 invertSelection = true 的值始终为 false。

于 2012-08-14T09:49:25.093 回答