D.R.
D.R.

Reputation: 21194

TakeWhile, at least n elements

There seems to be no e.TakeWhile(predicate, atLeastNElements) overload. Is there a convenient way to express TakeWhile, however, take at least N elements if there are >= N elements available.?

Edit: the best I came up with in my head is to capture an int in TakeWhile's predicate and reduce it by one each call while returning true. The actual predicate is used only after the counter is down to zero.

Upvotes: 4

Views: 586

Answers (1)

Kvam
Kvam

Reputation: 2218

You can use an overload to TakeWhile with the index of the current element:

var e = new [] { 1, 2, 3, 4, 5 };
var n = 3; // at least n
e.TakeWhile((element, index) => index < n || predicate(element));

Upvotes: 5

Related Questions