Is there a built-in/standard way of creating a deferred IEnumerable<T>
, given a Func<IEnumerable<T>>
? My Google skills may be weak...
Suppose I know that some method Foo
that returns an IEnumerable<T>
executes immediately (and is perhaps long-running). I want to pass it into method Bar
that takes in an IEnumerable<T>
but I don't want Foo
to be execute its long-running process to return items until Bar
starts iterating over the items:
IEnumerable<string> Foo()
{
var items = GetItems(); // long running process
return items;
}
void Bar(IEnumerable<string> foo)
{
/* something else long-running, or return immediately if some pre-condition fails and we don't even want to iterate over foo */
foreach (var item in foo)
{
// do something
}
}
void Run()
{
IEnumerable<string> foo = GetFooWrapper(Foo)
Bar(items);
}
IEnumerable<string> GetFooWrapper(Func<IEnumerable<string>> foo)
{
// ???
}
What's the best way of implementing GetFooWrapper
? My simplest approach was the following, but if there's some "better" way of doing it, I'd like to know about it. Not that it matters, but R# suggests simplifying it to return foo();
.
IEnumerable<string> GetFooWrapper(Func<IEnumerable<string>> foo)
{
foreach (var item in foo())
{
yield return item;
}
}