What is LINQ in C#: Simple Explanation and Example
LINQ (Language Integrated Query) in C# is a feature that lets you write queries directly in your code to work with data collections like arrays or lists. It makes data filtering, sorting, and selecting easier and more readable by using simple query syntax or method calls.How It Works
Think of LINQ as a smart assistant that helps you find and organize data inside your collections, like searching for books in a library. Instead of writing long loops and conditions, you write a simple query that describes what you want, and LINQ does the searching for you.
LINQ works by extending C# with special query keywords and methods that can be used on collections such as arrays, lists, or even databases. It translates your query into code that runs efficiently behind the scenes, making your code cleaner and easier to understand.
Example
This example shows how to use LINQ to find all even numbers in a list and print them.
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 }; var evenNumbers = from num in numbers where num % 2 == 0 select num; foreach (var n in evenNumbers) { Console.WriteLine(n); } } }
When to Use
Use LINQ when you need to work with collections of data and want to write clear, simple code to filter, sort, or transform that data. It is especially helpful when dealing with lists, arrays, or querying databases in C# applications.
For example, if you have a list of customers and want to find those from a specific city, LINQ lets you write that query in a way that reads almost like plain English, saving time and reducing errors.
Key Points
- LINQ integrates query capabilities directly into C# language.
- It works with many data sources like collections, XML, and databases.
- LINQ queries can be written using query syntax or method syntax.
- It improves code readability and reduces complexity.