I print this, I think, so that it shows the train of thought, as well as just the answer.
- Your source is cachedCrumbs only
- You want to add the first crumb that has IsCurrent but nothing after
- TakeWhile sounds like a way to go, but getting "IsCurrent has a previous meaning" is a bit of a pain.
- We can use closure to effectively save a variable that determines if the last value was set by IsCurrent
- We can do a few "no-op" so as not to distract TakeWhile from development, whether to continue
So, in the end we get:
bool foundCurrent = false; var crumbs = cachedCrumbs.TakeWhile(crumb => !foundCurrent) .Select(crumb => { foundCurrent = crumb == null || !crumb.IsCurrent; return crumb; });
I have not tried this, but I think it should work ... maybe easier.
EDIT: I would say that actually the direct foreach loop is simpler in this case. Having said that, you can write another extension method that acted like TakeWhile, except that it also returned the element that caused the condition to fail. Then it will be as simple as:
var crumbs = cachedCrumbs.NewMethod(crumb => crumb == null || !crumb.IsCurrent);
(I cannot come up with a decent name for the method at the moment, hence NewMethod !)
source share