When working with collections in C#, developers often need to filter, sort, and transform data. Traditionally, this required loops and conditional logic. But with LINQ (Language Integrated Query), you can query collections using a SQL-like syntax directly inside your C# code.
This makes your code cleaner, more readable, and easier to maintain.
🔹 What is LINQ?
LINQ is a set of features in C# that allows you to query data from different sources (arrays, lists, XML, databases) using a unified syntax. Think of it as bringing the power of SQL queries into your C# programs.
🔹 Why Use LINQ?
-
Readable: Queries look like SQL, making them intuitive.
-
Consistent: Same syntax for different data sources.
-
Powerful: Supports filtering, grouping, joining, and aggregation.
-
Concise: Reduces boilerplate code compared to loops.
🔹 Getting Started with LINQ
Let’s start with a simple example.
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string> { "Abhishek", "Ravi", "Priya", "Anita" };
// LINQ query
var query = from name in names
where name.StartsWith("A")
orderby name
select name;
foreach (var n in query)
{
Console.WriteLine(n);
}
}
}
Output:
Abhishek
Anita
🔹 LINQ Syntax Styles
LINQ supports two styles:
-
Query Syntax (SQL-like)
csharpvar result = from n in numbers where n > 5 select n; -
Method Syntax (Fluent style)
csharpvar result = numbers.Where(n => n > 5).Select(n => n);
Both produce the same result—choose whichever feels more natural.
🔹 Common LINQ Operations
-
Filtering
csharpvar adults = people.Where(p => p.Age >= 18); -
Sorting
csharpvar sortedNames = names.OrderBy(n => n); -
Grouping
csharpvar groups = people.GroupBy(p => p.City); -
Aggregation
csharpvar totalAge = people.Sum(p => p.Age);
🔹 Real-World Example
Imagine you have a list of students and want to find those scoring above 80:
var topStudents = from s in students
where s.Score > 80
orderby s.Score descending
select s.Name;
This is far more readable than writing nested loops and conditions.
🔹 Next Steps
Once you’re comfortable with the basics:
-
Explore joins (combine data from multiple collections).
-
Learn deferred execution (queries run only when iterated).
-
Use LINQ with Entity Framework for database queries.
🔹 Final Thoughts
LINQ transforms how you work with collections in C#. By adopting its SQL-like syntax, you’ll write cleaner, more efficient code that’s easier to understand. Whether you’re building educational apps or enterprise systems, LINQ is a skill worth mastering.