So after many hours of downloading I've acquired the March CTP for Orcas and have it running both at home and at work under Virtual PC 2007. I decided to jump into LINQ as I'm entirely jazzed about this but one of my first few experiments with it, while a little unorthodox, has me scratching my head a bit.
Consider if you will the following code, which retrieves a list of all files in the root folder of the C drive and then, using LINQ, selects a set of them at random using the FlipACoin method. Then I iterate through the list, outputting the contents of the results of my query ... or so I thought.
1: using System;
2: using System.Linq;
3: using System.Collections.Generic;
4: using System.Text;
6: namespace TestConsole07
8: class Program
10: static Random rnd = new Random();
12: static void Main(string args)
14: var myList =
15: from f in System.IO.Directory.GetFiles(@"C:\")
16: where FlipACoin()
17: select System.IO.Path.GetFileName(f);
20: Console.WriteLine("First Loop");
22: foreach (string loopFile in myList)
28: Console.WriteLine("Second Loop");
30: foreach (string loopFile in myList)
36: Console.WriteLine("Press Enter To Exit");
40: static bool FlipACoin()
42: return rnd.Next() > (int.MaxValue / 2);
When this code is executed, what happens is very odd. Here is the output from a sample run:
Press Enter To Exit
Notice that despite the fact that I'm iterating over the same list each time, the files listed are different. This means that each time I begin to iterate over the list the LINQ "query" is being executed again, and a new set of values are being returned from FlipACoin.
I can undoubtedly say this wasn't what I expected, but what I can't seem to determine is if this is a feature of LINQ or if this is a bug. My first response would be bug, but that is because whenever I believe I've expressed my intent clearly and don't get the response I expect, I call that a bug.
What do you think? Is this just a cool feature that won't come up very often? Or is this a dent in the armor of LINQ?