CSharp - Query Results Changing Between Enumerations

Introduction

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.

Demo

using System;
using System.Collections.Generic;
using System.Linq;
class Program//from  w  w  w. j a va  2  s  . c o 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)
            Console.WriteLine(i);

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


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

    }
}

Result

Related Topic