CSharp - Query Results Changing Between Enumerations


Queries returning IEnumerable<T> are deferred.

You can define the query once but use it multiple times by enumerating it multiple times.

Each time you enumerate the results, you will get different results if the data changes.

The following code shows an example of a deferred query where the query results are not cached and can change from one enumeration to the next.


using System;
using System.Collections.Generic;
using System.Linq;
class Program/*  w  w w .  ja  v a 2s.co  m*/
    static void Main(string[] args)

        //  Create an array of ints.  
        int[] intArray = new int[] { 1, 2, 3 };

        IEnumerable<int> ints = intArray.Select(i => i);

        //  Display the results.  
        foreach (int i in ints)

        // Change an element in the source data.  
        intArray[0] = 5;

        //  Display the results again.  
        foreach (int i in ints)



Related Topic