In this article, I will give a brief introduction to LINQ.
LINQ stands for Language Integrated Query. LINQ was introduced with .NET framework 3.5 and C# 3. LINQ belongs to System.Linq namespace. So, before writing LINQ query, we need to use that namespace. LINQ allows you to write structured and type safe queries. It allows you to query local data (e.g LINQ to Objects) as well as remote data (LINQ to SQL). You can query any data which implements IEnumerable<T> interface.
The basic building blocks of LINQ are sequences and elements. A sequence is an object that implements IEnumerable<T> interface and an element is each item in that sequence.
You can write a LINQ query in VB as well as C#. LINQ query can be written in three ways,
- Query expression
- Fluent Syntax
- Mixed Syntax
We will discuss all three syntaxes in the following example.
Query expression
Getting even number from given sequence using query syntax.
- int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
var result = from n in number
where n % 2 == 0
select n
foreach(int item in result) {
Console.WriteLine(item);
}
Output
Fluent Syntax
Getting even number from given sequence using fluent expression.
-
int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
var result = number.Where(x => x % 2 == 0);
foreach(int item in result) {
Console.WriteLine(item);
}
Output
Mixed Syntax
In mixed syntax type, you can use both query expression and fluent syntax in a single query.
- string[] name = new string[] {
- "ram",
- "sanju",
- "raju",
- "rakesh"
- };
- var result = (from s in name where s.EndsWith("u") select s).OrderBy(x => x.ToUpper());
- foreach(string item in result) {
- Console.WriteLine(item);
- }
Output
If you don’t want to use extension method, then you can write your query in the following way too.
- int[] number = new int[]{1,2,3,4,5,6,7,8,9 };
- var result = Enumerable.Where(number, x => x % 2 == 0);
- foreach(int item in result) {
- Console.WriteLine(item);
- }
Note
In the above example, the number issequence and each item is an element.
In the above example, "where" is an operator, and LINQ has around 40 operators. They are called standard query operators. An operator takes sequence as input and returns output.
In LINQ query, the data flows from left to right. Let’s understand this using the below example.
Example.
- string[] name = new string[] {
- "ram",
- "raju",
- "rakesh"
- };
- var result = name.Where(x => x.EndsWith("u")).Select(x => x.ToUpper());
- foreach(string item in result) {
- Console.WriteLine(item);
- }
Output
In this query, first the data is filtered (where), then result data is selected (select).
Compiler processes the query expression by translating it into fluent syntax. This means that anything that you can write in query syntax, you can also write in fluent syntax too.
Summary
In this article, we discussed the basics of LINQ and different ways of writing LINQ query.