Language Integrated Query (Linq) : Creating A LINQ Project

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 5

LANGUAGE INTEGRATED QUERY (LINQ)

Language-Integrated Query (LINQ) can be described as one the BEST features available with Visual Studio
2008 and .NET 3.5.

LINQ helps you to work with Data as Objects and Query, Access, Modify and Manipulate them. With Visual Studio
2008 we can write queries in C# or VB.NET. You can query against any object which can also be a SQL Server
Database or XML documents or ADO.NET datasets or any collection of objects that supports IEnumerable or
IEnumerable interfaces.

This blog post deals on how to get started with LINQ with Visual Studio 2008 and C#.

Creating a LINQ Project


The basic requirement for your project to support LINQ is it has to be a .NET 3.5 Framework project. Once you
create a project with .NET 3.5, it adds the necessary references to support LINQ

Our LINQ Sample Project


I have a taken a very simple example to illustrate the power of LINQ. Here is the class diagram of our project,

We have an array of names from which we are going to the following:

1) Display all names in the array


2) Display first ‘n’ names in the array
3) Filter the names by a character match
4) Filter by a specific Name
5) Split the names by first character and rest
LINQ Actions
Before getting into our sample, I would like to tell that any LINQ query operation consists of the following
actions,

Our query expression syntax looks like this,

We now have a new data type var where the compiler determines the type that is associated and assigns the
most appropriate when the query result is returned.

string name = "Chaks";


var strSplit = name.Split('a');

In our above example, the compiler determines that the type of the strSplit to be String and assigns it. Please
understand that the keyword var doesn’t mean that it is loosely typed.

Our First Query


Let us get started with our first utility function which is to display all names in our names array
If you are familiar with SQL, then you should be able to follow our query too. It’s fairly simple – From array
names, take each array element into a variable called name and select them all

Here our array is nothing but an IEnumerable object which allows us to query against them and return the value
in the variable query. If you check the type of the variable query, you will see that it’s nothing but of type
IEnumerable which confirms us that the query selects all the names in the array of type String. You can check the
type by,

Console.WriteLine("query Type==>{0}", query.GetType().ToString());

Query Execution
The above query doesn’t result in the execution, instead the query variable stores the actual query commands
and it gets executed until it’s used or really needed. This is called Deferred Execution.

When we say that query doesn’t get executed, then what does the variable query holds? – It holds an object that
can give values that we would want to have

Get to know more about Deferred Executions here.

So, the above query will be executed only when we start iterating the foreach loop, which is shown below,

But there are also sometimes that the query has to be executed immediately and one such example is,

int length = names.Count();

In the above example, the query has to be executed to get the count of elements. Similarly if you want to force
immediate query and cache those results, we can do something like,

IEnumerable [string] query =


(from name in names
where name == matchName
select name).ToList();

The above query is forced to execute immediately and cache the results in a local variable query

Moving Forward
Our first query didn’t do much other than just returning all the names. Let us go to another utility function which
filters the array of names by a Name
IEnumerable[string] query =
from name in names
where name == matchName
select name;

Now we have our Where clause where our condition is specified and the rest looks same as in our first query. One
thing to note in the above query is that we have explicitly specified the type of our query result to
be IEnumerable[string] instead of var. So, LINQ also allows specifying query return types explicitly.

Method Based Query Syntax


All the above examples were using the query expression syntax which is similar to SQL syntax. You can also query
using method-based syntax, which is,

IEnumerable[string] query = names


.Where(n => n.Equals(matchName))
.Select();

The above query is equivalent of writing,

IEnumerable[string] query =
from name in names
where name == matchName
select name;

The only difference is that we have used method-based query syntax. The method-based syntax is defined
as Extension Methods of the type they operate on and they also make use of Lambda Expressions.

Support for Anonymous Types


LINQ allows us to define and use anonymous types in our query results. Take this for an example,

var query =
from name in names
select new
{
firstPart = name[0],
lastPart = name.Substring(1, (name.Length - 1))
};

We define two anonymous types - firstPart and lastPart and when we query now, we get,
let Clause
Sometimes it becomes a necessity to store the result of another sub-expression in a query and use it later.

We can do this with the let keyword, which creates a new range variable and initializes it with the result of that
sub-expression we specify. Let us re-write the above query which we used for anonymous types to use let
keyword,

var query =
from name in names
let firstPart = name[0]
let lastPart = name.Substring(1, (name.Length - 1))
select new { firstPart, lastPart };

You might also like