How could I take 1 more item from Linq's TakeWhile?

后端 未结 5 2027
难免孤独
难免孤独 2021-01-01 16:45

(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

5条回答
  •  遥遥无期
    2021-01-01 17:40

    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);
    

提交回复
热议问题