Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Objects: TakeWhileOrFirst

What would be the most readable way to apply the following to a sequence using linq:

TakeWhile elements are valid but always at least the first element

EDIT: I have updated the title, to be more precise. I'm sorry for any confusion, the answers below have definitely taught me something!

The expected behavior is this: Take while element are valid. If the result is an empty sequence, take the first element anyway.

like image 235
asgerhallas Avatar asked Dec 21 '22 18:12

asgerhallas


1 Answers

I think this makes the intention quite clear:

things.TakeWhile(x => x.Whatever).DefaultIfEmpty(things.First());

My earlier, more verbose solution:

var query = things.TakeWhile(x => x.Whatever);
if (!query.Any()) { query = things.Take(1); }
like image 52
Botz3000 Avatar answered Jan 08 '23 23:01

Botz3000