Linq deferred execution -


i wrote simple program, here's looks like, details hidden:

using system; using system.collections.generic; using system.linq; using system.text; using system.io;  namespace routeaccounts {     class program     {         static void main(string[] args)         {             //draw lines source file             var lines = file.readalllines("accounts.txt").select(p => p.split('\t'));             //convert lines accounts             var accounts = lines.select(p => new account(p[0], p[1], p[2], p[3]));             //submit accounts router             var results = accounts.select(p => routeaccount(p));             //write results list target file             writeresults("results.txt", results);         }          private static void writeresults(string filename, ienumerable<result> results)         {             ... disk write call ...         }          private static result routeaccount(account account)         {             ... service call ...         }     } } 

my question - obviously, when selecting data context, execution deferred. if notice, in first statement of 'main' function, i'm querying file.readalllines("accounts.txt"). bad choice? if enumerate final result, statement repeatedly?

i can .toarray() or grab results ahead of time, if know it's problem, i'm interested know what's going on behind scenes.

it's not going read file repeatedly, no - because that part of execution isn't deferred. return array, , call select return sequence... projection deferred, reading of file won't. array stay in memory until referring (directly or indirectly) eligible garbage collection... won't need reread file.

on other hand, may want read results using tolist() or similar anyway - because way, find out errors before start write results. it's quite idea make sure you've got data need before start executing code side effects (which imagine writeresults does). it's less efficient in terms of amount of data needed in memory @ time though... it's balance you'll have weigh yourself.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -