开发者

Retrieve IEnumerable's method parameters

开发者 https://www.devze.com 2023-01-25 13:13 出处:网络
Consider this method: public IEnumerable<T> GetList(int Count) { foreach (var X in Y) { // do a lot of expensive stuff here (e.g. traverse a large HTML document)

Consider this method:

public IEnumerable<T> GetList(int Count)
{
    foreach (var X in Y)
    {
        // do a lot of expensive stuff here (e.g. traverse a large HTML document)
        // when we reach "Count" then exit out of the foreach loop
    }
}

and I'd call it like so: Class.GetList(10); which would return 10 items - this is fine.

I'd like to use IEnumerable's Take() method by using Class.GetList().Take(10) instead and I want the foreach loop to be able to somehow grab the number I passed into Take() - is this possible? It seems a more cleaner approach as it's ultimately less expensive as I can grab a full list with Class.GetList() once and then use IEnumerable's methods to grab x items afterwards.

Thank开发者_运维知识库s guys!


You can do this by implementing your method as an iterator block:

public IEnumerable<T> GetList()
{
    foreach (var X in Y)
    {
        // do something
        yield return something;
    }
}

When you call Take(10) only the first 10 elements will be yielded - the rest of the method won't be run.


In your GetList method use yield return. This way you will be able to use Take(10) without the GetList method returning the entire result first.


No, this is not possible. However, what Take(10) does is that it just gets 10 items of the Enumerable. What you are trying to accomplish with the Count check, the Take() does this for you because it will simply stop getting items from your enumerator when it has 10 items.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号