Breaking the loop using TakeWhile when count or length condition is met

I'm trying to figure out a way to use TakeWhile to break a loop when some conditions are met.

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 would like to do is write that instead of using Linq instead of

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 to

+3


source to share


2 answers


You don't need it here TakeWhile

- just filter the elements that match your condition and take no more than 10 matching elements:

children.Where(x => x.ContentTypeID == 123).Take(10)

      



TakeWhile

takes all elements as long as any condition is met. But you don't need to grab all of the items - you want to skip over the items that are not required ContentTypeID

.

+4


source


The received response addresses the message. This answer is about the title.

TakeWhile and Take can be used together. TakeWhile will stop at the first mismatch, and Take will stop after a certain number of matches.



var playlist = music.TakeWhile(x => x.Type == "Jazz").Take(5);

      

+1


source







All Articles