Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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

like image 484
Eric Herlitz Avatar asked Nov 24 '25 19:11

Eric Herlitz


2 Answers

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.

like image 114
Sergey Berezovskiy Avatar answered Nov 27 '25 11:11

Sergey Berezovskiy


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);
like image 45
Amy B Avatar answered Nov 27 '25 11:11

Amy B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!