Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TakeWhile, at least n elements

Tags:

c#

linq

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.

like image 369
D.R. Avatar asked Oct 26 '25 11:10

D.R.


1 Answers

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));
like image 186
Kvam Avatar answered Oct 29 '25 00:10

Kvam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!