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

前端 未结 6 2115
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  一整个雨季
    2021-02-05 08:51

    Not to be too obvious but...

    int max = Math.Min(6, rss.Channel.Items.Count);
    for (int i = 0; i < max; i++)
    {
       var rssItem = rss.Channel.Items[i];
       //...
    }
    

    I know it's old school, and not filled with all sorts of Extension method goodness, but sometimes the old school still works... especially if you're still using .NET 2.0.

提交回复
热议问题