Using ToList() method to force LINQ query execute immediately

when using LINQ TO SQL, results of query dose not retrieve until you consume results or on the other hand you iterate in results.

in example, assume you have a table in database that keeps users specifications such as Firstname, Lastname and so on.

and assume that you use a Object Relational Designer to execute queries against database and user's table.

by means of calling ToList() method, you force LINQ to execute immediately and return actual results.

in conclude you can use the following code to save items in cache memory.


List<Users> lstUsers = (List<Users>) Cache["Users"];
if
(lstUsers == null)
{
   SampleDataContext db = new SampleDataContext();
   lstUser = db.Users.ToList();
   Cache[
"Users"] = lstUser;
}
GridView1.DataSource = lstUsers;
GridView1.DataBind();

Have a good time.

3 Comments

  • Hi,

    I'm new in linq, but want to do something like the above sample.

    While retrieving a product I want also to retrieve it's price (many item in database) and it's category (many to many in database)

    I want all data to return in a list of product.

    Can you give me any idea what should be the code for this?

    public List&lt;Product&gt; FindProducts(string search)

    {

    var result = from a in Context.Products

    where a.name.startswith(search)

    ?????

    return result.ToList();

    }
    -------------------------------------------------------
    Hi Robin
    I did not understand your exactly mean.
    but this work is related to database structure and design. if you want retrieve product details from one table and product category in another table, simple way is create database view and join this two table and then make Linq to the view.
    I hope be helpful.

  • Does ToDictionary acheive the same effect?


    ----------------------------

    @Ryan
    yes, ToArray, ToDictionary, ToList, and ToLookup have the same effect

  • as per definition in msdn,

    &quot;The ToList&lt;(Of &lt;(TSource&gt;)&gt;)(IEnumerable&lt;(Of &lt;(TSource&gt;)&gt;)) method forces immediate query evaluation and returns a List&lt;(Of &lt;(T&gt;)&gt;) that contains the query results. You can append this method to your query in order to obtain a cached copy of the query results.&quot;

    then is it required to use cache?

Comments have been disabled for this content.