Simply LINQ: What,Why and How.
What is LINQ?
LINQ is Language-Integrated Query (LINQ). It is primarily an extension to the language’s capability where it adds query expressions which processes objects and data.
It is a one stop solution to all the query processing as now there is no need to learn a different query language for each type of data source: SQL databases, XML documents etc.
- Type safe.
- IntelliSense support.
- Tables are available as classes.
- SQL generated is well structured and optimized.
- Targets Business rules.
- Easy to debug with the visual studio’s debugger.
- Easy to deploy as being a part of DLL.
- LINQ to SQL parameterizes input so better security.
- And,best of all, SIMPLE.
var Employee= from emp in Employees where emp.name="CodeSpread" select emp;
Let’s see the flow, First the ‘from’ clause points to the data source which is ‘Employees’. Next, ‘where’ specifies the filter which is the employee name. Lastly, ‘select’ statement returns the result set.
There are three main components of LINQ.
- Standard Query Operators
- Language Extensions
- LINQ Providers
Standard Query Operators:
The standard query operators can be simply referred to as methods in LINQ .There are two sets of LINQ standard query operators,
var result= from emp in Employees orderby emp.empid select emp.name;
But it doesn’t look like method, let’s write it again.
var result= Employees. Select(emp=>emp.name).OrderBy(emp=> emp.empid);
Looks good now. Both of the above examples just vary in syantax. There are many other Standard Query Operators available which we will enlist in a future article.
These are data source-specific implementations for ex: in-memory object collections, Microsoft SQL Server databases, ADO.NET datasets and XML documents.
- LINQ to Objects – Executes a LINQ query against a collection of objects
For an in-memory object collections like arraylist of employees,
var result= from emp in empList where emp.name="CodeSpread" select emp;
- LINQ to XML – Executes an XPATH query against XML documents.
XElement root= XElement.Load("\..\Employees.xml"); IEnumerable employee= root.Elements();
- LINQ to SQL – Executes LINQ queries against Microsoft SQL Server.
For a Database called company and table called customers.
IQueryable customer = from cust in company.Customers where cust.name== "CodeSpread" select cust;
- LINQ to ADO.NET datasets- Executes LINQ queries against ADO.NET DataSets.
Same example as above where the data is queried from a dataset instead of directly from a table.