LINQ (Language Integrated Query) is a powerful feature in C# that enables you to query, filter, and manipulate data in a more readable and concise way. It provides a consistent query experience for working with different types of data, including collections, arrays, databases, XML, and more, directly within C# code.
Key Features of LINQ
1. Declarative Syntax: LINQ queries are written in a readable, SQL-like syntax, making code easier to understand and maintain.
2. Language Integration: Queries are executed in the same language you are programming in, which reduces the need to learn and manage multiple query languages (e.g., SQL for databases).
3. Type Safety: LINQ queries are strongly typed, meaning compile-time checking is performed, reducing the chances of runtime errors.
4. Extensibility: LINQ works with any collection that implements IEnumerable or IQueryable, allowing you to query objects, arrays, lists, and more.
Types of LINQ Syntax
There are two common ways to write LINQ queries in C#
1. Query Syntax (SQL-like)
Query syntax is more readable and looks like a SQL query. It starts with from, where, select, and other SQL-like keywords.
Syntax like:
// Array of integers
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// query Syntax
var oddNumbers = from num in numbers
where num % 2 != 0
select num;
// Output the result
foreach (var num in oddNumbers)
{
Console.WriteLine(num);
}
}
}
Complete Example:
using System;
using System.Linq;
public class MyProgram
{
public static void Main(string[] args)
{
// Array of integers
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var oddNumbers = from num in numbers
where num % 2 != 0
select num;
// Output the result
foreach (var num in oddNumbers)
{
Console.WriteLine(num);
}
}
}
Output:
3
5
7
9
Explanation:
- from num in numbers: Loops through each element in the array.
- where num % 2 != 0: Filters the numbers to only include odd ones.
- select num: Projects the filtered numbers to the result.
2. Method Syntax
Method syntax uses LINQ extension methods like Where(), Select(), OrderBy(), etc.
Syntax like:
// Array of integers
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Method syntax
var evenNumbers = numbers.Where(num => num % 2 == 0);
Complete Example:
using System;
using System.Linq;
public class MyProgram
{
public static void Main(string[] args)
{
// Array of integers
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Method syntax
var evenNumbers = numbers.Where(num => num % 2 == 0);
foreach (var num in evenNumbers)
{
Console.WriteLine(num);
}
}
}
Output:
4
6
8
10