Last active
December 15, 2015 01:19
-
-
Save GregRos/5179050 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var delayed_list = | |
from item in Enumerable.Range(0, 1000).DelayedList() | |
where item%2 == 0 | |
select item*2; | |
// This is a 'delayed list'. | |
//Basically it is implicitly capable of producing a real List collection if we choose to force it. | |
//Before we do, we can just perform a few more LINQ queries... | |
var delayed_list2 = | |
from item in delayed_list | |
where item % 3 == 0 | |
select item; | |
//Right now, performing a second LINQ query basically disposes of the previous delayed list. | |
//We don't want to end up allocating lists for no reason after all. | |
//One way to force the evaluation of the list is an implicit conversion. | |
List<int> real_list = delayed_list2; | |
//Another way to force it is to iterate over it. | |
//However, because the delayed list has been evaluated iterating over it like this | |
//Would just give us the List's IEnumerator. Meaning the list is cached internally. | |
foreach (var item in delayed_list2) | |
{ | |
Console.Write("{0}, ", item); | |
} | |
//We can do another LINQ query on it | |
var y = from item in x | |
where item%4 == 0 | |
select item*9; | |
//Getting another delayed list. | |
//This has quite a few holes in it and is just for demonstration purposes. | |
//In general, it would work a lot better if instead of List we had an immutable data structure. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment