Breaking a loop using TakeWhile when a count or length condition is meet

Viewed 592

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

2 Answers
Related