CSharp - Returning a List So the Query Is Executed Immediately and the Results Are Cached

Description

Returning a List So the Query Is Executed Immediately and the Results Are Cached

Demo

using System;  
using System.Collections.Generic;
using System.Linq;  
class Program//  w  w  w  .j  a v  a  2  s  .c o m
{
    static void Main(string[] args)
    {
              //  Create an array of ints.  
              int[] intArray = new int[] { 1, 2, 3 };  
                
              List<int> ints = intArray.Select(i => i).ToList();  
                
              //  Display the results.  
              foreach(int i in ints)  
                Console.WriteLine(i);  
                
              // Change an element in the source data.  
              intArray[0] = 5;  
                
              Console.WriteLine("---------");  
                
              //  Display the results again.  
              foreach(int i in ints)  
                Console.WriteLine(i);  
                     
    }
}

Result

Notice the results do not change from one enumeration to the next.

This is because the ToList method is not deferred.

The query is actually performed at the time the query is called.

Related Topic