Ine*_*elp 0 c# linq where conditional-statements
我有以下方法:
public static List<string> GetArgsListStartsWith(string filter, bool invertSelection, bool lowercaseArgs)
{
return GetArgumentsList(lowercaseArgs)
.Where(x => !invertSelection && x.StartsWith(filter)).ToList();
}
Run Code Online (Sandbox Code Playgroud)
然后我就这样称呼它 GetArgsListStartsWith("/", true, false)
这将转化为:获取所有不以"/"开头的参数列表.问题是列表没有填充,即使所有参数都不以"/"开头.
如果我调用GetArgsListStartsWith("/", false, false)哪个转换为:获取以"/"开头的所有参数的列表,则列表将填充以"/"开头的参数.
我怀疑当设置为true并返回false 时!invertSelection && x.StartsWith(filter)不会返回,但我不明白为什么.有人看到我不喜欢的东西吗?trueinvertSelectionx.StartsWith(filter)
至于其他的答案说,你的病情只会永远当返回true invertSelection是假的.
有条件地反转结果的最简单方法是使用XOR运算符:
.Where(x => x.StartsWith(filter) ^ invertSelection)
Run Code Online (Sandbox Code Playgroud)
我更喜欢这个而不是lc的解决方案,因为它只指定了StartsWith一次.
.Where(x => invertSelection ? !x.StartsWith(filter) : x.StartsWith(filter))
Run Code Online (Sandbox Code Playgroud)