I'm trying to figure out a way to use TakeWhile to break a loop when some conditions are meet.
i.e.
var i = 0;
List<IContent> t = new List<IContent>();
// children is a List<> with lots of items
foreach (var x in children)
{
if (i >= 10)
{
break;
}
if (x.ContentTypeID == 123)
{
i++;
t.Add(x);
}
}
What I'd like to do is to write that using Linq instead
var i = 0;
var a = children.TakeWhile(
x =>
{
if (i >= 10)
{
break; // wont work
}
if (x.ContentTypeID == 123)
{
i++;
return true;
}
return false;
});
Any ideas? Thanks
You don't need a TakeWhile here - simply filter items which match your condition and take no more than 10 of matched items:
children.Where(x => x.ContentTypeID == 123).Take(10)
TakeWhile takes all items while some condition is met. But you don't need to take all items - you want to skip those items which don't have required ContentTypeID.
The accepted answer addresses the post. This answer addresses the title.
TakeWhile and Take can be used together. TakeWhile will stop on the first non-match and Take will stop after a certain number of matches.
var playlist = music.TakeWhile(x => x.Type == "Jazz").Take(5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With