Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

LINQ – Language Integrated Query

4.00/5 (1 vote)
15 May 2011CPOL2 min read 7K  
LINQ – Language Integrated Query

Introduction

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 operations rely 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 infered using initialization.

The var keyword can be used only for Local variables, which are initialized with a non-null value.

Following are a few examples where var is used:

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

Following are a few examples where var is used wrongly:

C#
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 initializes an object in the object creation statement itself. It reduces the steps required to create an object and sets the designated properties accordingly.

The following object initializer is:

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

same as:

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

Anonymous Types

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

Examples of using anonymous types are:

C#
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 member of the Extended Types.

An Extension Method must be a public static method hosted inside a static class. Use the this keyword before the parameter of the 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:

C#
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 use the functional language syntax and are more concise. It is a more compact and type-safe way of defining a statement. Lambda expressions pass functions as arguments for later evaluation.

A few examples of Lambda expressions are:

C#
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 a SQL like syntax, which will get compiled to C# using Extension Methods.

A few examples of query expression are:

C#
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 };

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)