Wednesday, January 9, 2008

LINQ : Introduction to LINQ

LINQ is Microsoft’s technology to provide a language-level support mechanism for querying data of all types. These types include in-memory arrays and collections, databases, XML documents, and more.

LINQ is all about queries, whether they are queries returning a set of matching objects, a single object, or a subset of fields from an object or set of objects. In LINQ, this returned set of objects is called a sequence. Most LINQ sequences are of type IEnumerable<T>, where T is the data type of the objects stored in the sequence.

For example, if you have a sequence of integers, they would be stored in a variable of type IEnumerable.

Example 1 : Collections (By adding using directive for the System.Linq namespace.)

using System;
using System.Linq;

string[] greetings = {"hello world", "hello LINQ", "hello Apress"};

var items =

from s in greetings
where s.EndsWith("LINQ")

select s;

foreach (var item in items)

Console.WriteLine(item);

OUTPUT:

hello LINQ

----------------------------------------------------------------------------------------------

Example 2 : XML (By adding using directive for the System.Xml.Linq namespace.)

using System;
using System.Linq;
using System.Xml.Linq;

XElement books = XElement.Parse(
@"<employees>
<employee>
<name>Arjun Kannan</name>
<dept>IT</dept>
</employee>
<employee>
<name>Nivas Nair</name>
<dept>IT</dept>
</employee>
<employee>
<name>Pandiaya Gopi Babu</name>
<dept>Fianace</dept>
</employee>
<employees>
");

var depts=
from e in employees.Elements("employee")
where (string) employee.Element("dept") == "IT"
select e.Element("name");

foreach(var dept in depts)
Console.WriteLine(dept.Value);

OUTPUT :

Arjun Kannan
Nivas Nair

----------------------------------------------------------------------------------------------

Example 3 : SQL (By adding using directive for the System.Data.Linq namespace.)

using System;
using System.Linq;
using System.Data.Linq;
using nwind;

Northwind db = new Northwind(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind");

var custs =
from c in db.Customers
where c.City == "Rio de Janeiro"
select c;

foreach (var cust in custs)
Console.WriteLine("{0}", cust.CompanyName);

OUTPUT :

Hanari Carnes
Que Delícia
Ricardo Adocicados


Hope you like this!!! Share your thoughts with me !!!
- Rangoli