(感兴趣的代码行是最后一个,剩下的只是一个完整的表示)我怎么能从Linq的TakeWhile中拿出更多的物品?
使用下面的代码,我想采取VOTERS直到我超过所需的最大票,但它就停在达到最大数量的选票之前,我的选民池比我想要的要少一个选民。
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));
注意:记住'voicesSoFar'在循环结束时是不正确的,它是一个辅助变量。 – Kobi 2010-02-11 05:27:54
+1对于不需要编写不必要的扩展方法的解决方案。 – 2010-02-11 05:33:40
这很奇怪,但我不能得到第一个版本来展示任何东西......尽管如此,单线程仍然完美。 – 2010-02-11 05:36:41