Immediate Query Execution

   
 

using System;
using System.Linq;

class MainClass {
    static double Square(double n) {
        Console.WriteLine("Computing Square(" + n + ")...");
        return Math.Pow(n, 2);
    }

    public static void Main() {
        int[] numbers = { 1, 2, 3 };
        var query = from n in numbers select Square(n);
        foreach (var n in query.ToList())
            Console.WriteLine(n);
    }
}

    


Deferred Query Execution

   
 

using System;
using System.Linq;

class MainClass {
    static double Square(double n) {
        return Math.Pow(n, 2);
    }
    public static void Main() {
        int[] numbers = { 1, 2, 3 };
        var query = from n in numbers select Square(n);
        foreach (var n in query)
            Console.WriteLine(n);
    }
}

    


Shows how queries can be reused

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class MainClass {
public static void Main() {
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNumbers =
from n in numbers
where n <= 3 select n; Console.WriteLine("First run numbers <= 3:"); foreach (int n in lowNumbers) { Console.WriteLine(n); } for (int i = 0; i < 10; i++) { numbers[i] = -numbers[i]; } Console.WriteLine("Second run numbers <= 3:"); foreach (int n in lowNumbers) { Console.WriteLine(n); } } } [/csharp]

How queries can be executed immediately with operators such as ToList().

   
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class MainClass {
    public static void Main() {
        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)
            .ToList();

        // The local variable i has already been fully
        // incremented before we iterate the results:
        foreach (var v in q) {
            Console.WriteLine("v = {0}, i = {1}", v, i);
        }
    }
}

    


Using DefaultIfEmpty in Where clause

   
 

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class MainClass {
    public static void Main() {
        string[] presidents = {"G", "H", "a", "H", "over", "Jack"};

        string jones = presidents.Where(n => n.Equals("H")).DefaultIfEmpty().First();
        if (jones != null)
            Console.WriteLine("H was found.");
        else
            Console.WriteLine("H was not found.");
    }
}

    


Without Using DefaultIfEmpty

   
 

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class MainClass {
    public static void Main() {

        string[] presidents = {"G", "H", "a", "H", "over", "Jack"};

        string jones = presidents.Where(n => n.Equals("H")).First();
        if (jones != null)
            Console.WriteLine("H was found");
        else
            Console.WriteLine("H was not found");

    }
}