How do I limit the number of elements iterated over in a foreach loop?

前端 未结 6 2130
伪装坚强ぢ
伪装坚强ぢ 2021-02-05 08:34

I have the following code

foreach (var rssItem in rss.Channel.Items)
{
    // ...
}

But only want 6 items not all items, how can I do it in C#?

6条回答
  •  猫巷女王i
    2021-02-05 09:01

    You could also just break out of the loop if you don't want to use linq.

            int count = 0;
            foreach (var rssItem in rss.Channel.Items)
            {
                if (++count == 6) break;
                ...
            }
    

提交回复
热议问题