is there built-in/standard way of creating deferred ienumerable<t>
, given func<ienumerable<t>>
? google skills may weak...
suppose know method foo
returns ienumerable<t>
executes (and perhaps long-running). want pass method bar
takes in ienumerable<t>
don't want foo
execute long-running process return items until bar
starts iterating on items:
ienumerable<string> foo() { var items = getitems(); // long running process return items; } void bar(ienumerable<string> foo) { /* else long-running, or return if pre-condition fails , don't want iterate on foo */ foreach (var item in foo) { // } } void run() { ienumerable<string> foo = getfoowrapper(foo) bar(items); } ienumerable<string> getfoowrapper(func<ienumerable<string>> foo) { // ??? }
what's best way of implementing getfoowrapper
? simplest approach following, if there's "better" way of doing it, i'd know it. not matters, r# suggests simplifying return foo();
.
ienumerable<string> getfoowrapper(func<ienumerable<string>> foo) { foreach (var item in foo()) { yield return item; } }
sounds you're looking lazy<t>
class. defers creation of object until first used.
here's example defer execution of foo
method until value
property accessed first time. once foo
executed once, not executed again unless new lazy<t>
created.
var items = new lazy<ienumerable<string>>(foo); foreach(var item in items.value) // delay starts here { // work }
Comments
Post a Comment