Sreenivas Mogullapalli

Microsoft Technologies Geek
posts - 44, comments - 39, trackbacks - 6

My Links

News



Archives

Post Categories

.NET Framework

SQL Server

Introduction to LINQ (Language Integrated Query)

Introduction to LINQ (Language Integrated Query)

 

Language Integrated Query (LINQ) is a set of features that extends query capabilities to the language syntax. It is designed to bridge the gap between the world of objects and world of data.

 

At present, queries are embedded in to language as simple string and there is no type checking at compile type or no support of IntelliSense in development. LINQ makes a query a first-class language construct in C# and Visual Basic. You can write LINQ queries in Visual Basic or C# with SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<(Of <(T>)>) interface.

 

The C# 3.0 language introduce several new language features that are useful individually or collectively for doing LINQ.

 

The following are the new features of C# 3.0 supporting LINQ

 

Implicitly Typed Local Variables

The “var” keyword is used to infer the type of the variable from the assignment expression. The inferred type can be a built-in type, an anonymous type, a user-defined type or any expression.

 

Example:

var sTemp = “Hello world”;

foreach ( var SingleItem in Collection) { ... }

 

The var keyword does not indicate that the variable is loosely-coupled or late-bound. The compiler determines the appropriate type and assigns to the variable.

 

Object and Collection Initializers

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

 

Examples:

// Object initializer

    Student student = new Student {Id = 10, Name = "Bob" };

 

Collection Initializers let you specify one or more element initializers when you initialize a collection class instead of multiple calls to add method class.

 

Examples:

// Collection Initializers

List<int> numbers = new List<int> {0, 1, 2};

 

Extension Methods

Extension methods is the capability to add methods to existing types without creating a derived type.  Extension methods are defined as static method but they are used as if they are instance methods of that type.

 

Example:

namespace ExtensionMethods

{

    public static class MyExtensions

    {

        public static int WordCount(this String str)

        {

            return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;

        }

    }  

}

 

The WordCount extension method can be brought into scope with this using directive:

 

using ExtensionMethods;

 

And it can be called from an application by using this syntax:

 

string s = "Hello Extension Methods";

int i = s.WordCount();

 

Anonymous types

An anonymous type is a way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. Compiler generates the type name and infers the types for the properties. Anonymous types are created by using the new operator with an object initializer. Anonymous types are class types that consist of one or more public read-only properties.  An anonymous type has method scope.

 

Example:

var newVar = new { Id = 1, Name = "Bob" };

 

Lambda Expressions

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

 

Example:

Expression<del> = x => x * x;

 

Auto-Implemented Properties

Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. Compiler creates a private, anonymous backing field can only be accessed through the property's get and set accessors.

 

Example:

public string Name { get; set; }

 

LINQ Queries

Normally we write queries to retrieve data from data source (ex: database) in a specific query language. LINQ is offering a consistent programming model for accessing data from different data sources. In a LINQ query you deal with objects and same coding pattern is used across different data sources.

 

var qCustomers = from customer in customers

                           where customer.City == "London"

                           select customer;

 

We need to specify the data source first in writing LINQ Query. The “from” clause is used to mention the data source and a range variable. The “let” clause can be used for additional range variables. The “where” clause is used to filtering the result set. LINQ has additional clauses that can be used to sort the results or do aggregate values using group by options.

 

LINQ to Objects

LINQ queries can be applied to any enumerable collections. Collection could be List, Array or any other collection which implements IEnumerable. This does not require any intermediate LINQ provider or API.

 

LINQ to objects provides a new approach to collections by declaratively defining what you want to retrieve.

 

LINQ to XML

Interaction with in-memory XML programming is redesigned and supported by LINQ. You can use similar query like interface on DOM objects to retrieve XML information. You can write queries on the in-memory XML document to retrieve collections of elements and attributes.

 

Example:

IEnumerable<string> partNos =

    from item in purchaseOrder.Descendants("Item")

    select (string) item.Attribute("PartNumber");

 

LINQ to ADO.NET (LINQ to databases)

LINQ to ADO.NET consists of two concepts: LINQ to dataset and LINQ to SQL.

 

LINQ to DataSet

Interaction with DataSet is improved by LINQ capabilities. LINQ to DataSet can be applied to data in DataSet that is consolidated from different data sources, one or many. LINQ to DataSet improves the performance by making it easier and faster to query data stored in DataSet. LINQ to Dataset provides benefits like compile-time syntax checking, static typing and IntelliSense support which improves the developer productivity and reduces the common errors like misspelled field names. LINQ queries can be performed against single tables in a DataSet or against more than one table by using the Join and GroupJoin standard query operators.

 

LINQ queries are supported against both typed and untyped DataSet objects. In a typed DataSet, the tables and rows have typed members for each of the columns, which makes queries simpler and more readable.

 

In addition to the standard query operators implemented in System.Core.dll, LINQ to DataSet adds several DataSet-specific extensions that make it easier to query over a set of DataRow objects. These DataSet-specific extensions include operators for comparing sequences of rows, as well as methods that provide access to the column values of a DataRow.

 

Example:

// Fill the DataSet.

DataSet ds = new DataSet();

ds.Locale = CultureInfo.InvariantCulture;

FillDataSet(ds);

 

DataTable products = ds.Tables["Product"];

 

IEnumerable<DataRow> productsQuery =

    from product in products.AsEnumerable()

    select product;

 

IEnumerable<DataRow> largeProducts =

    productsQuery.Where(p => p.Field<string>("Size") == "L");

 

Console.WriteLine("Products of size 'L':");

foreach (DataRow product in largeProducts)

{

    Console.WriteLine(product.Field<string>("Name"));

}

 

LINQ to SQL

LINQ to SQL is a run-time infrastructure for managing relational data as objects.  In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, LINQ to SQL translates into SQL the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, LINQ to SQL translates them back to objects that you can work with in your own programming language.

 

By using LINQ to SQL, you can use the LINQ technology to access SQL databases just as you would access an in-memory collection.

 

Example:

// Northwnd inherits from System.Data.Linq.DataContext.

Northwnd nw = new Northwnd(@"northwnd.mdf");

 

var companyNameQuery =

    from cust in nw.Customers

    where cust.City == "London"

    select cust.CompanyName;

 

foreach (var customer in companyNameQuery)

{

    Console.WriteLine(customer);

}

 

To implement LINQ to SQL in your application you need to follow the steps

  1. Create the object model

Meta data of an existing database is represented as object model.  This can be generated by using Object Relational Designer, SQLMetal Code Generation Tool or custom generated code using code editor.

This object model can be saved in c# or VB, an XML file or a DBML file.

Optionally, you can make modification to the saved object model before it can be used in your project.

  1. Use the object Model

Once the object model is generated, it can be used to retrieve the data, manipulate the data or send updates back to database.

Tools

Visual Studio 2008 provides handful of tools that support development using LINQ.

Object Relational Designer: The Object Relational Designer is a visual design tool that you can use in LINQ to SQL applications to generate classes in C# or Visual Basic that represent the relational data in an underlying database.

SQLMetal Command Line Tool: A tool that can be used to generate classes from existing databases for use in LINQ to SQL purpose.

Code Editor: Visual Studio provides IntelliSense and formatting capabilities for LINQ in code editors of c# and VB.

Debugging: Using Visual Studio, you can debug the query expressions.

 

Technical References

msdn.microsoft.com

Microsoft MSDN Library 2008

 

Print | posted on Sunday, December 09, 2007 8:33 PM |

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: