Deferred Execution and Immediate Execution in LINQ

Deferred Execution executes the query only when Loop starts. What I mean here is that, we iterate through the query variable to get the result.
  

clip_image001

  

Here the result variable does not contain the actual result. To get the result, we may iterate through the result (query) variable in loop as many time as we want. We do deferred execution mainly when multiple values is being returned from the query.

  

Example

  


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

namespace ConsoleApplication3
{
 class Program
 {
 static void Main(string[] args)
 {
 DataClasses1DataContext context = new DataClasses1DataContext();
 var result = from r in context.Persons select r;
 foreach (var a in result)
 {
 Console.WriteLine(a.FirstName + "" + a.LastName);
 }
 Console.ReadKey(true);

 }
 }
}

  

Output
clip_image003

  

Immediate Execution happens when LINQ query returns a single value.

  

clip_image005

  

Above query is returning a single value so it can be executed immediately.

  

Example

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

namespace ConsoleApplication3
{
 class Program
 {
 static void Main(string[] args)
 {
 DataClasses1DataContext context = new DataClasses1DataContext();
 var numberOfRecords = (from r in context.Persons select r).Count();
 Console.WriteLine(numberOfRecords);
 Console.ReadKey(true);

}
 }
}

  

Output
clip_image007

  

If we want to make a query returning multiple values or sequence of values as immediate then we need to explicitly convert the result in ToList().

  

clip_image009

  

So above query is returning multiple values and would be executed immediately.
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication3
{
 class Program
 {
 static void Main(string[] args)
 {
 DataClasses1DataContext context = new DataClasses1DataContext();
 var result1 = (from r in context.Persons select r).ToList();
 foreach (var a in result1)
 {
 Console.WriteLine(a.FirstName + "" + a.LastName);
 }
 Console.ReadKey(true);
 }
 }
}
Output
clip_image011

Var versus IEnumerable in LINQ

We have seen normally
clip_image002
Or
clip_image004
Now question is where to use var or IEnumerable? Let us first have a look on both key words
Var derives type from the right hand side. And its scope is in the method. And it is strongly typed. IEnumerable is interface which allows forward movement in the collection.
Now in LINQ where to use what ?
If we really do not have idea that what would be the type of query then we will be using var. and if we are sure about the type of output then we would be using IEnumerable .
Using IEnumerable <T>
In the below example, we are querying in collection of string so we know the output would be collection of string, so we are using here IEnumerable with string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> lstStrings = new List<string> {"Dhananjay Kumar",
                                                         "Mahesh Chand",
                                                         "John papa",
                                                         "Mike Gold",
                                                         "Shiv Prasad Koirala",
                                                          "Victor ",
                                                           "Pinal Dave" };
            IEnumerable<string> result = from r in lstStrings select r;
            foreach (var r in result)
            {
                Console.WriteLine(r);
            }
            Console.ReadKey(true);
        }
    }
}

Output
clip_image006
Using var
Now if we don’t know exactly what would be the type of result in that case we will be using var. There might be some scenario where you want to return anonymous type from the query
clip_image008
If you see the above query we do not know the type of result.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            DataClasses1DataContext context = new DataClasses1DataContext();
            var result = from r in context.Persons select new { NameOfperson = r.FirstName + r.LastName };
            foreach (var r in result)
            {
                Console.WriteLine(r.NameOfperson);
            }
            Console.ReadKey(true);
        }
    }
}

Output
clip_image010

Listing columns name with type of a table using LINQ

After my last post, I got a question asking how to list all the Column names of a given table using LINQ.

Before going through this post, I recommend you to read Get All the Tables Name using LINQ

Let us say, you have a table called dbo.Person and you need to find all the columns of this particular table. 
So first we need to find whether table exists in DataContext or not 

clip_image002

Dbo.Person is name of the table.
We are looking through all the tables and finding where given table exists or not. Once we get table we need to list the entire columns name
clip_image003

Full source code is as below. In below code we are finding whether dbo.Person table is existing or not. If existing in DataContext then listing all the columns name

 

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            DataClasses1DataContext context = new DataClasses1DataContext();
            var datamodel = context.Mapping;


            foreach (var r in datamodel.GetTables())
            {
                if (r.TableName.Equals("dbo.Person", StringComparison.InvariantCultureIgnoreCase))
                {

                    foreach (var r1 in r.RowType.DataMembers)
                    {
                        Console.WriteLine(r1.MappedName);
                    }
                }

            }
            Console.ReadKey(true);
        }
    }
}

Output
clip_image005