KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
(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 ));
Tags (comma-separated)
Save Edits
Cancel