2013-08-14 18 views
5

Potresti spiegare perché l'output di queste due funzioni è diverso per gli stessi dati?
Mi aspettavo che producessero lo stesso output, ad esempio linee di accodamento. Come posso cambiare l'alternativa 1 per aggiungere linee?Espressione Linq e foreach producono risultati diversi

(Sfondo Measurements implementa ICollection<>)

alternativi 1

private void CreateBody(TestRun testRun, StringBuilder lines) 
{ 
    testRun.Measurements.OrderBy(m => m.TimeStamp) 
     .Select(m => lines.AppendLine(string.Format("{0},{1}", m.TestRound, m.Transponder.Epc))); 
} 

-/linee> non Rese

alternativi 2

private void CreateBody2(TestRun testRun, StringBuilder lines) 
{ 
    foreach (Measurement m in testRun.Measurements.OrderBy(m => m.TimeStamp)) 
    { 
     lines.AppendLine(string.Format("{0},{1}", m.TestRound, m.Transponder.Epc)); 
    } 
} 

-> linee aggiunte per ogni misurazione

risposta

9

Poiché l'esecuzione dei ritardi di linq, pertanto, la selezione non avverrà mai (poiché si sta eseguendo la selezione e quindi si esce dal metodo), mentre foreach eseguirà l'esecuzione proprio nel momento in cui si esegue il metodo. È necessario enumerare il risultato che si sta selezionando. Ad esempio, eseguendo ToList() o ToArray() per forzare il metodo a enumerare, o si potrebbe adottare un approccio completamente diverso.

private void CreateBody(TestRun testRun, StringBuilder lines) 
{ 
    testRun.Measurements.OrderBy(m => m.TimeStamp).ToList().ForEach(m => lines.AppendLine(string.Format("{0},{1}", m.TestRound, m.Transponder.Epc))); 
} 
+0

Lazy Evaluation è il termine. [Articolo su Lazy vs Eager] (http://blogs.msdn.com/b/ericwhite/archive/2006/10/04/lazy-evaluation-_2800_and-in-contrast_2c00_-eager-evaluation_2900_.aspx) – bland

Problemi correlati