我有一个 bool 列表和一个字符串列表。我想使用 IEnumerable.Zip 组合列表,因此如果第一个列表的每个索引处的值为真,则结果包含第二个列表中的相应项目。
换句话说:
List<bool> listA = {true, false, true, false};
List<string> listB = {"alpha", "beta", "gamma", "delta"};
IEnumerable<string> result = listA.Zip(listB, [something]);
//result contains "alpha", "gamma"
我能想到的最简单的解决方案是:
listA.Zip(listB, (a, b) => a ? b : null).Where(a => a != null);
...但我怀疑有一种更简单的方法可以做到这一点。有吗?
最佳答案
我觉得这样更简单:
listA
.Zip(listB, (a, b) => new { a, b } )
.Where(pair => pair.a)
.Select(pair => pair.b);
这在逻辑上将步骤分开。首先,合并列表。接下来,过滤。没有时髦的条件,只需从头到尾阅读并立即理解。
你甚至可以适本地命名它:
listA
.Zip(listB, (shouldIncludeValue, value) => new { shouldIncludeValue, value } )
.Where(pair => pair.shouldIncludeValue)
.Select(pair => pair.value);
我喜欢 self 记录、明显的代码。
关于c# - Linq:使用 Zip 排除结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21052639/