C# | LINQ
Language-Integrated Query (LINQ) in C# is used to work with data access from sources such as objects, data sets, SQL Server, and XML. LINQ stands for Language Integrated Query. LINQ is a data querying API with SQL like query syntaxes. LINQ provides functions to query cached data from all kinds of data sources. The data source could be a collection of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.
The official goal of the LINQ family of technologies is to add "general purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data".
Advantages of LINQ
- LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So, through LINQ we can query database, XML as well as collections.
- Compile time syntax checking
- It allows you to query collections like arrays, enumerable classes etc. in the native language of your application, like VB or C# in much the same way as you would query a database using SQL
LINQ to Object
LINQ to Object provides functionality to query in-memory objects and collections. Any class that implements the IEnumerable<T> interface (in the System.Collections.Generic namespace) can be queried with SQO.
LINQ to ADO.NET
LINQ to ADO.NET deals with data from external sources, basically anything ADO.NET can connect to. Any class that implements IEnumerable<T> or IQueryable<T> (in the System.Query namespace) can be queried with SQO.
- LINQ to SQL (DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported}
- LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables}
- LINQ to Entities
LINQ to XML (XLinq)
LINQ to XML is used to query XML data sources.
Here is a detailed tutorial on LINQ with C# for beginners.
LINQ Code Examples
Here is a simple example that creates a array of integers. A LINQ query is used to return a var that stores the collection of returned data. Learn more: The var keyword in C#.
Let's look at a working example. Create a Web page or UI with a GridView control that we will use to display some data. The following code example defines a class, patient with some properties such as name, gender, age, and area.
Now, on the Web Page (ASP.NET Web Forms in this case), we create a List object dynamically. This program adds a single record but you an add a collection of records. Once the collection is ready, LINQ can be used to query the collection.
In this code, a recorded is queired using LINQ and displayed in a GridView control.
Main Program
The following code uses the selection operator type, which brings all those records whose age is more than 20 years.
The following code snippet uses the grouping operator type that group patient data on the bases area.
Linq Example
Simple select
Multiple select
Order by
Count function
Comments
Post a Comment