Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Linq Question
Message
From
15/07/2010 05:03:38
Cetin Basoz
Engineerica Inc.
Izmir, Turkey
 
General information
Forum:
ASP.NET
Category:
LINQ
Title:
Miscellaneous
Thread ID:
01472512
Message ID:
01472536
Views:
57
>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
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Previous
Reply
Map
View

Click here to load this message in the networking platform