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!
You can do this by implementing your method as an iterator block:
When you call
Take(10)only the first 10 elements will be yielded – the rest of the method won’t be run.