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

后端 未结 5 2024
难免孤独
难免孤独 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:39

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

    public static IEnumerable TakeUntilIncluding(this IEnumerable list, Func 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.

提交回复
热议问题