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 numberwhere n % 2 == 0select nforeach(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.



Join the conversation! Your thoughts help the community grow.