(感兴趣的代码行是最后一行,其余的只是为了完整表示)
使用以下代码,我想获取 VOTERS 直到我超过所需的最大票数,但它在达到最大票数之前停止,因此我的选民池中的选民比我少 1 个通缉。
在 LINQ 中是否有一种干净的方法可以让它进行投票,直到达到最大投票数?我知道我可以再添加一个投票者或在循环中执行此操作,但我很好奇是否有一种好的方法可以使用 LINQ 来执行此操作。
var voters = new List<Person>
{
new Person("Alice", Vote.Yes ),
new Person("Bob", Vote.Yes),
new Person("Catherine", Vote.No),
new Person("Denzel", Vote.Yes),
new Person("Einrich", Vote.Abstain),
new Person("Frederica", Vote.Abstain),
new Person("Goeffried", Vote.Abstain),
};
voters.Single(c => c.Name == "Alice").Voices = 100;
voters.Single(c => c.Name == "Bob").Voices = 150;
voters.Single(c => c.Name == "Catherine").Voices = 99;
voters.Single(c => c.Name == "Denzel").Voices = 24;
voters.Single(c => c.Name == "Einrich").Voices = 52;
voters.Single(c => c.Name == "Frederica").Voices = 39;
voters.Single(c => c.Name == "Goeffried").Voices = 99;
// this takes voters until we are BEFORE reaching X voices...
int voicesSoFar = 0;
int voicesNeeded = 300;
var eligibleVoters = voters.TakeWhile((p => (voicesSoFar += p.Voices) < voicesNeeded ));
最佳答案
在我想要执行一个函数直到并包括它达到结束条件的情况下,我这样做了:
public static IEnumerable<T> TakeUntilIncluding<T>(this IEnumerable<T> list, Func<T, bool> predicate)
{
foreach(T el in list)
{
yield return el;
if (predicate(el))
yield break;
}
}
为我工作!我认为这是一个与 Jason 类似的与实现无关的解决方案,但更简单。
关于c# - 我怎样才能从 Linq 的 TakeWhile 中再拿 1 件元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2242318/