>Consider this example:
>
>
>public static void Example1()
>{
>
> List<string> people = new List<string>()
> {
> "Granville", "John", "Ross", "Betty",
> "Chandler", "Rachel", "Monica", "Ruby"
> };
>
>
> //IEnumerable<string> query = from p in people
> // where p.StartsWith("R")
> // orderby p
> // select p;
>
> var query = (from p in people
> where p.StartsWith("R")
> orderby p
> select p).ToList();
>
>
> foreach (string person in query)
> {
> Console.WriteLine(person);
> }
> Console.WriteLine("Press any key to continue");
> Console.ReadLine();
>}
>
>
>What is the difference between the commented query and the uncommented query?
As Rob said,
One is a query (definition) and the other is a result of that query as a List< string >.
First one's type is IEnumerable< string > and second one's is List< string >.
ToList() causes a list to be generated and takes a "snapshot" of the matching values. From there on it have a constant value if you only read and do not add anything to the result (query). Changes in 'people' doesn't effect the 'query'. All foreach() iterations would return initial set of 3 values.
OTOH first one doesn't enumerate and take the matches until you do something on it that invokes enumeration (ie: foreach() call). That means each call to second one might yield different results depending on changes in 'people'. ie: Try this with each:
people.Add("Rendered New Item");
Console.WriteLine ("\nAfter adding a new item");
Console.WriteLine ("{0} items", query.Count());
foreach (var person in query)
{
Console.WriteLine(person);
}
Cetin