开发者

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

开发者 https://www.devze.com 2022-12-20 07:16 出处:网络
(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

(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.Sing开发者_运维问答le(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 ));


In a situation where I wanted to execute a function until and including it hit an end condition I did:

public static IEnumerable<T> TakeUntilIncluding<T>(this IEnumerable<T> list, Func<T, bool> predicate)
{
    foreach(T el in list)
    {
        yield return el;
        if (predicate(el))
            yield break;
    }
}

Worked for me! I think this is an implementation-agnostic solution like Jason's, but simpler.


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


Just write your own extension method:

static class IEnumerableExtensions {
    public static IEnumerable<T> TakeUntil<T>(
        this IEnumerable<T> elements,
        Func<T, bool> predicate
    ) {
        return elements.Select((x, i) => new { Item = x, Index = i })
                       .TakeUntil((x, i) => predicate(x.Item))
                       .Select(x => x.Item);
    }

    public static IEnumerable<T> TakeUntil<T>(
        this IEnumerable<T> elements,
        Func<T, int, bool> predicate
    ) {
        int i = 0;
        foreach (T element in elements) {
            if (predicate(element, i)) {
                yield return element;
                yield break;
            }
            yield return element;
            i++;
        }
    }
}

Usage:

var eligibleVoters = voters.TakeUntil(
                         p => (voicesSoFar += p.Voices) >= voicesNeeded
                     );

foreach(var voter in eligibleVoters) {
    Console.WriteLine(voter.Name);
}

Output:

Alice
Bob
Catherine


Variation of Kobi's answer but demonstrates use of (value, index). index is useful in solving similar issues albeit not OP's.

voters.TakeWhile((value, index) => (voicesSoFar += value.Voices) - value.Voices < voicesNeeded);


I was facing the same problem. I have used Union and Skip methods, so to take until it was

   IEnumerable<Something> newSomethings  = somethings.TakeWhile(s => s != stop).Union(new List<Something>(){stop});  

and for skip until

   IEnumerable<Something> newSomethings  = somethings.SkipWhile(s => s != stop).Skip(1);  

There is also Take method, which takes some int of first results.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号