Author : MD TAREQ HASSAN | Updated : 2021/03/22
What is LINQ?
- LINQ: Language Integrated Query
- Language Integrated: means that LINQ is part of programming language syntax
- Query: a query is an expression that retrieves data from a data source
- Data source: NET collections, streams, SQL databases, in-memory representations, XML etc
- LINQ is a Microsoft programming model and methodology that essentially adds formal query capabilities into .NET-based programming languages
- LINQ offers a compact, expressive, and intelligible syntax for manipulating data
- LINQ is uniform query syntax to retrieve data providing a single querying interface for different types of data sources
- LINQ is a way of providing a general purpose “querying” mechanism in the CLR
- Result from a LINQ operation:
IEnumerable<T>
IQueryable<T>
There 2 types of LINQ syntax:
- Query syntax
- Method syntax
Consist of three distinct actions:
- Obtain the data source
- Create the query
- Execute the query
Query syntax
// 1. Data source
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation. numQuery is an IEnumerable<int>
var numQuery = from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution
foreach (int num in numQuery)
{
}
Method syntax
- Method syntax uses lambda expression
- Lambda expression: syntactic sugar for passing lambda as argument to higher order function
// 1. Data source
int[] numbers = { 5, 10, 8, 3, 6, 12};
// 2. Query creation. numQuery is an IEnumerable<int>
IEnumerable<int> numQuery = numbers.Where(num => num % 2 == 0).OrderBy(n => n);
// 3. Query execution
foreach (int i in numQuery)
{
Console.Write(i + " ");
}