(的$ C $感兴趣C线是最后一个,剩下的只是一个完整的重新presentation)
使用下面的code,我想利用选民,直到我的超过的最大需要票,但它停止达到这一票数最多,所以我的选民池有1较少的前右选民不是我想要的。
有没有干净的方式在LINQ在那里我可以使人们进行表决,直到它达到了票的最大数目?我知道我可以添加更多的选民,也可以做到这一点在一个循环中,但我很好奇,如果有一个很好的方式来使用LINQ做到这一点吧。
VAR选民=新的名单,其中,人物>
{
新的Person(爱丽丝,Vote.Yes)
新的Person(鲍勃,Vote.Yes)
新的Person(凯瑟琳,Vote.No)
新的Person(丹泽尔,Vote.Yes)
新的Person(Einrich,Vote.Abstain)
新的Person(弗雷德里卡,Vote.Abstain)
新的Person(Goeffried,Vote.Abstain)
};
voters.Single(C => c.Name ==爱丽丝)的声音= 100。
voters.Single(C => c.Name ==鲍勃)的声音= 150。
voters.Single(C => c.Name ==凯瑟琳)的声音= 99。
voters.Single(C => c.Name ==丹泽尔)的声音= 24。
voters.Single(C => c.Name ==Einrich)的声音= 52。
voters.Single(C => c.Name ==弗雷德里卡)的声音= 39。
voters.Single(C => c.Name ==Goeffried)的声音= 99。
//这需要选民,直到我们才到达X的声音...
INT voicesSoFar = 0;
INT voicesNeeded = 300;
VAR eligibleVoters = voters.TakeWhile((P =>(voicesSoFar + = p.Voices)< voicesNeeded));
解决方案
您正在寻找
voters.TakeWhile(P => {
布尔超过= voicesSoFar> voicesNeeded;
voicesSoFar + = p.Voices;
收益率超过!;
});
如果你坚持一个班轮,这将通过比较previous价值的工作:
voters.TakeWhile(P =>(voicesSoFar + = p.Voices) - p.Voices< voicesNeeded);
(line of code of interest is the last one, the rest is just for a full representation)
Using the following code, I wanted to take VOTERS until I exceeded the maximum votes needed, but it stops right before reaching that maximum number of votes, so my voters pool has 1 fewer voter than I wanted.
Is there a clean way in LINQ where I could have made it take votes UNTIL it reached the maximum numbers of votes? I know I could add one more voter or do this in a loop but I am curious if there was a good way to do this with LINQ instead.
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 ));
解决方案
You're looking for
voters.TakeWhile(p => {
bool exceeded = voicesSoFar > voicesNeeded ;
voicesSoFar += p.Voices;
return !exceeded;
});
If you insist on a one-liner, this will work by comparing the previous value:
voters.TakeWhile(p => (voicesSoFar += p.Voices) - p.Voices < voicesNeeded);