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

前端 未结 6 2126
伪装坚强ぢ
伪装坚强ぢ 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:55

    If you're interested in a condition (i.e. ordering by date created)

    foreach(var rssItem in rss.Channel.Items.OrderByDescending(x=>x.CreateDate).Take(6)) 
    {
    //do something
    }
    

    Perhaps if you want to get those created by a certain user, with that same sort

    foreach(var rssItem in rss.Channel.Items
                              .Where(x=>x.UserID == 1)
                              .OrderByDescending(x=>x.CreateDate)
                              .Take(6)) 
    {
    //do something
    }
    

提交回复
热议问题