linq Deferred Execution

The following sample shows how query execution is deferred until the query is enumerated at a foreach statement.
public static void Deferred_Execution()
        {
            // Sequence operators form first-class queries that
            // are not executed until you enumerate over them.

            int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

            int i = 0;
            var q =
                from n in numbers
                select ++i;

            // Note, the local variable 'i' is not incremented
            // until each element is evaluated (as a side-effect):
            foreach (var v in q)
            {
                Console.WriteLine("v = {0}, i = {1}", v, i);
            }
        }
Output


linq Deferred Execution linq Deferred Execution Reviewed by Bhaumik Patel on 4:23 AM Rating: 5