LINQ – Language Integrated Query


LINQ is the new query language used in .Net to query any kind of data source. LINQ can be used to query data from XML, SQL Server, Excel, etc.

LINQ operation relies on Type Inferencing, Type Initializers, Anonymous Types, Extension Methods, Lambda Expressions and Query Expressions.

Type Inferencing

Type inferencing means inferring the correct type at compile time. LINQ uses the keyword ‘var’ to declare the type of a query result. At compile time, the type is infers using the initialization.

var’ keyword can be used only for Local variables, which are initialized with a not null value.

Following are few examples, where ‘var’ is used

var c = new Customer("Bob", "Smith", 1234); var c = default(string);

Following are few examples, where ‘var’ is used wrongly.

             var c;        
            var c = null; 
            public var DoSomething(int x){}  
            public void DoSomething(var x){} 

 Type Initializers

LINQ uses the object initializer feature of .Net. Object Initializer is initialize an object in object creation statement itself. It reduces the steps required to create an object and sets the designated properties accordingly.

The following Object initializer is

         Invoice i = new Invoice () { CustomerId = 123, Name = "Test” };

 Same as

           Invoice invoice = new Invoice();
            invoice.CustomerId = 123;
            invoice.Name = "Test";

 Anonymous Types

We can use the object initializers without any type definition. Also, we can define a result as anonymous.

Few examples, where we used the anonymous types are

            var i2 = new Invoice { CustomerId = 123, Name = "SmithCo" };
           var i3 = new {CustomerId = 123, Name = "SmithCo" };
            var i4 = new {123, "SmithCo"};
 

This generates a class corresponding to the result. LINQ uses Anonymous types frequently.

Extension Methods

Extension methods are methods used to extend the functionality of an existing type. This method will add new functionality to an existing type without defining any derived class. Extensions methods can access any public members of Extended Types.

Extension methods must be a public static method hosted inside a static class. Use this keyword before parameter of extended type.

Anonymous Method

C# 2.0 introduced anonymous methods. With delegates, we can inject code to another method.

An example of an anonymous method is

       delegate void Display(string s); 
        public class Anonymous 
        { 
          static void Main() 
          { 
            
            Display d = delegate(string j) 
            { 
                System.Console.WriteLine(j); 
            }; 

            d("Call delegate using the anonymous method");   
          } 
        }

 

 Lambda Expressions

Lambda expressions are based on anonymous methods. Lambda expressions uses the functional language syntax and more concise. It is more compact and type-safe way of defining a statement. Lambda expressions pass functions as arguments for later evaluation.

Few examples of Lambda expression are

             Func<int, int> addOne = n => n + 1;
            Console.WriteLine(addOne(5)); // Print 6

            Expression<Func<int, int>> addOneExpression = n => n + 1;
            var addOneFunc = addOneExpression.Compile();
            Console.WriteLine(addOneFunc(5)); // Print 6

 Query Expressions

Query expressions define a new query language with SQL like syntax, which will get compiled to C# using extension methods.

Few examples of query expression are

         from c in container.Categories 
select new { Name = c.CategoryName, c.Products, ProductCount = c.Products.Count })
    .OrderBy(c => c.Name).ToList().ForEach(c => Console.WriteLine("{0, -14} has {1} products.", c.Name, c.ProductCount)

 

 

         from c in context.Categories
         select new { Name = c.CategoryName, c.Products, ProductCount = c.Products.Count };

 

About ambilykk

I am a Technology Evangelist on Microsoft Technologies. I am carrying the passion on Microsoft technologies specifically on web technologies such as ASP .Net and Ajax. My interests also include Azure and Visual Studio. Technology adoption and learning is my key strength and technology sharing is my passion.
This entry was posted in LINQ and tagged , , , , , , , . Bookmark the permalink.

Leave a comment