Blog Detail

Introduction to LINQ

05 Jun 10
No Comments
Language Integrated Query, or LINQ, is a Microsoft technology introduced in the .NET 3.5 framework. LINQ lets you “…write queries against strongly typed collections of objects.” That is, it lets you treat a variety of data – not just databases – as first class data sources. LINQ comes in several flavors to allow you to talk to diverse data sources, including databases, XML streams, and even objects in your program (lists, arrays, dictionaries, etc.). LINQ provides several powerful advantages over more traditional approaches: more concise code; filter, group, and ordering capabilities with little coding; portability due to a common query language for all data sources; and strong typing.

A LINQ query operation consists of just three steps: obtain a data source, create a query, and execute the query. This canonical example from Microsoft’s Introduction to LINQ Queries page clearly illustrates the three steps:

class IntroToLINQ
static void Main()
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// 2. Query creation.
// evenNumQuery is an IEnumerable
var evenNumQuery =
from num in numbers
where (num % 2) == 0
select num;

// 3. Query execution.
foreach (int num in evenNumQuery)
Console.Write(“{0,1} “, num);
In this example, the data source is simply an array of integers, and the query – with its use of keywords like from, where, and select – resembles a SQL query, though the ordering of clauses is different. It is significant to note that defining the query is separate from its execution. Not until the foreach loop does the data source return any results (which in this case is just a list of the even numbers from the array).

Leave A Comment