Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve IEnumerable's method parameters

Tags:

c#

ienumerable

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.

Thanks guys!

like image 553
eth0 Avatar asked Dec 21 '22 21:12

eth0


1 Answers

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.

like image 113
Mark Byers Avatar answered Dec 24 '22 10:12

Mark Byers