Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You have a very nasty problem that arises from mutating an outer variable to the lambda expression. The problem is this: if you try to iterate <code>eligibleVoters</code> twice (<code>foreach(var voter in eligibleVoters) { Console.WriteLine(voter.Name); }</code> and immediately after (<code>foreach(var voter in eligibleVoters) { Console.WriteLine(voter.Name); }</code>) you will not see the same output. That is just not right from a functional programming perspective.</p> <p>Here is an extension method that will accumulate until some condition on the accumulator is true:</p> <pre><code>public static IEnumerable&lt;T&gt; TakeWhileAccumulator&lt;T, TAccumulate&gt;( this IEnumerable&lt;T&gt; elements, TAccumulate seed, Func&lt;TAccumulate, T, TAccumulate&gt; accumulator, Func&lt;TAccumulate, bool&gt; predicate ) { TAccumulate accumulate = seed; foreach(T element in elements) { if(!predicate(accumulate)) { yield break; } accumulate = accumulator(accumulate, element); yield return element; } } </code></pre> <p>Usage:</p> <pre><code>var eligibleVoters = voters.TakeWhileAccumulator( 0, (votes, p) =&gt; votes + p.Voices, i =&gt; i &lt; 300 ); </code></pre> <p>Thus the above says accumulate voices while we have accumulated less than 300 votes.</p> <p>Then with:</p> <pre><code>foreach (var item in eligibleVoters) { Console.WriteLine(item.Name); } Console.WriteLine(); foreach (var item in eligibleVoters) { Console.WriteLine(item.Name); } </code></pre> <p>Output is:</p> <pre><code>Alice Bob Catherine Alice Bob Catherine </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload