1. 🔎 What is LINQ?
  2. 🌟 Why Use LINQ?
  3. 📝 Examples of LINQ in Action
    1. 1. LINQ with Lists
    2. 2. Method Syntax
    3. 3. LINQ with Complex Objects
  4. ✅ Conclusion

When working with data in C#, developers often need to filter, sort, or transform collections. Traditionally, this involved writing long loops and conditional statements. But with LINQ (Language Integrated Query), introduced in .NET, you can handle these tasks with clean, concise, and SQL-like syntax—directly inside your C# code.


🔎 What is LINQ?

LINQ stands for Language Integrated Query. It’s a powerful feature in C# that allows you to query and manipulate data in a way that looks very similar to SQL. Unlike raw SQL strings, LINQ queries are strongly typed and benefit from IntelliSense and compile-time checking.

LINQ is not limited to databases—it can be applied to:

  • Collections (Lists, Arrays, Dictionaries, etc.)
  • Databases (through Entity Framework or LINQ to SQL)
  • XML, JSON, DataSets, and more

🌟 Why Use LINQ?

  • Readable and concise – eliminates boilerplate loops.
  • Strongly typed – errors are caught at compile time.
  • Flexible – works across multiple data sources.
  • Powerful – supports filtering, ordering, grouping, joining, projections, and aggregations.

📝 Examples of LINQ in Action

1. LINQ with Lists
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6 };

        // Query syntax: Get even numbers greater than 2
        var evenNumbers = from n in numbers
                          where n % 2 == 0 && n > 2
                          select n;

        Console.WriteLine("Results:");
        foreach (var num in evenNumbers)
        {
            Console.WriteLine(num);
        }
    }
}

Output:

4
6

2. Method Syntax

LINQ queries can also be written using extension methods:

var evenNumbers = numbers.Where(n => n % 2 == 0 && n > 2);

3. LINQ with Complex Objects
var employees = new List<Employee>()
{
    new Employee { Id = 1, Name = "John", Salary = 1000 },
    new Employee { Id = 2, Name = "Alice", Salary = 2000 },
    new Employee { Id = 3, Name = "Bob", Salary = 1500 }
};

// Get employees with salary > 1500
var highSalary = employees.Where(e => e.Salary > 1500)
                          .OrderByDescending(e => e.Salary);

foreach (var emp in highSalary)
{
    Console.WriteLine($"{emp.Name} - {emp.Salary}");
}

Output:

Alice - 2000

✅ Conclusion

LINQ in C# is more than just a shortcut—it’s a paradigm shift in how developers work with data. By combining the power of SQL-like queries with the safety and flexibility of C#, LINQ allows you to write clean, efficient, and maintainable code.

If you’re a C# developer and haven’t yet embraced LINQ, now is the perfect time to start. It will not only make your code shorter but also more expressive and easier to maintain.