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

前端 未结 6 2125
伪装坚强ぢ
伪装坚强ぢ 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 09:15

    Use Enumerable.Take:

    foreach(var rssItem in rss.Channel.Items.Take(6)) {
        // go time!
    }
    

    Note that

    rss.Channel.Items.Take(6)
    

    does not do anything except instantiate an implementation of IEnumerable that can be iterated over to produce the first six items in the enumeration. This is the deferred execution feature of LINQ to Objects.

    Note further that this assumes .NET 3.5. If you are working with an earlier version of .NET, you could use something along the lines of the following:

    static IEnumerable Take(IEnumerable source, int take) {
        if (source == null) {
            throw new ArgumentNullException("source");
        }
        if (take < 0) {
            throw new ArgumentOutOfRangeException("take");
        }
        if (take == 0) {
            yield break;
        }
        int count = 0;
        foreach (T item in source) {
            count++;
            yield return item;
            if (count >= take) {
                yield break;
            }
        }
    }
    

    Then:

    foreach(var rssItem in Take(rss.Channel.Items, 6)) {
        // go time!
    }
    

    This assumes .NET 2.0. If you're not using .NET 2.0 you should seriously consider upgrading.

提交回复
热议问题