ASP.Net – Introducing LINQ

LINQ stands on Language Integrated Query. LINQ changes the way you access and query data. Before LINQ was created, most queries were expressed as text that was executed against a database. This SQL text was often specific to the underlying technology of the database being queried. LINQ elevates the process of querying for data to actual language constructs and keywords. This has two primary advantages: First, it provides type checking of your query code at compile time; this means that you are likely to encounter fewer errors, you can use IntelliSense, and it will be easier to write code. Second, it provides a consistent model for querying against all database technologies and all data, including lists, XML, arrays, database tables, and more.

LINQ and IEnumerable

LINQ queries introduce several contracts and keywords to Visual Basic and C#. These keywords allow you to write queries against anything that supports the base interface, IEnumerable or IEnumerable<T>. In the .NET Framework, this means nearly all collections of data, including DataSet, List<T>, Array, and many more. For example, assuming that you have a list of Employee objects named employees, the following LINQ query code would return all employees working in the IT department from that list.

Example in Visual Basic

Dim empQuery As IEnumerable(Of Employee) = From emp In employees
Where emp.Department = "IT Department"
Select emp

Example in C#

IEnumerable<Employee> empQuery = from emp in employees
where emp.Department == "IT Department"
select emp;

Notice that the LINQ query is actually saved to a typed variable, in this case IEnumerable<Employee>. You can save your query to what are called queryable types. The common ones are IEnumerable<T> and IQueryable<T>. These allow the query to actually automatically examine (“iterate over”) each piece of data when executed. You can skip using this typed syntax and simply use the var keyword in C# or no type value in Visual Basic to declare your query variable. The following shows an example.

Example in Visual Basic

Dim empQuery = From emp In employees
Where (emp.Department = "IT Department")
Select emp

Example in C#

var empQuery = from emp in employees
where emp.Department == "IT Department"
select emp;