LINQ Bug or Feature?
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;
5:
6: namespace TestConsole07
7: {
8: class Program
9: {
10: static Random rnd = new Random();
11:
12: static void Main(string[] args)
13: {
14: var myList =
15: from f in System.IO.Directory.GetFiles(@"C:\")
16: where FlipACoin()
17: select System.IO.Path.GetFileName(f);
18:
19: Console.WriteLine();
20: Console.WriteLine("First Loop");
21: Console.WriteLine("-----------");
22: foreach (string loopFile in myList)
23: {
24: Console.WriteLine(loopFile);
25: }
26:
27: Console.WriteLine();
28: Console.WriteLine("Second Loop");
29: Console.WriteLine("-----------");
30: foreach (string loopFile in myList)
31: {
32: Console.WriteLine(loopFile);
33: }
34:
35: Console.WriteLine();
36: Console.WriteLine("Press Enter To Exit");
37: Console.ReadLine();
38: }
39:
40: static bool FlipACoin()
41: {
42: return rnd.Next() > (int.MaxValue / 2);
43: }
44: }
45: }
When this code is executed, what happens is very odd. Here is the output from a sample run:
First Loop
----------
AUTOEXEC.BAT
eula.1033.txt
install.ini
install.res.1033.dll
MSDOS.SYS
NTDETECT.COM
ntldr
pagefile.sys
sde.bmp
SDE_VSD.MSI
unicows.dllSecond Loop
-----------
boot.ini
CONFIG.SYS
install.exe
install.ini
install.res.1033.dll
NTDETECT.COM
SDE_VSD.MSI
unicows.dllPress 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?