C# LINQ (Language Integrated Query)

What is LINQ?

LINQ (Language Integrated Query) allows you to query and manipulate data in collections like lists and arrays.

It provides a clean and readable way to filter, sort, and transform data.

Loading...
Output:

Filtering Data (Where)

The Where() method filters elements based on a condition.

Only elements that satisfy the condition are returned.

Loading...
Output:

Transforming Data (Select)

The Select() method transforms each element into a new form.

This is useful for modifying data without changing the original collection.

Loading...
Output:

Sorting Data

LINQ provides methods to sort data easily.

Use OrderBy() for ascending and OrderByDescending() for descending order.

Loading...
Output:

First and Single

LINQ can retrieve single elements using methods like First().

These methods are useful when you only need one result.

Loading...
Output:

Aggregation (Sum, Count, Average)

LINQ provides built-in methods to calculate values from collections.

These are useful for statistics and data analysis.

Loading...
Output:

Lambda Expressions

LINQ uses lambda expressions to define conditions and transformations.

A lambda is a short way to write functions.

Loading...
Output:

Real-World Example

LINQ is often used to process collections of objects.

Loading...
Output:

Why LINQ is Important

LINQ is widely used in modern C# development.

  • Used in databases (Entity Framework)
  • Cleaner than loops
  • Improves readability

Practice

Create a list of numbers and use LINQ to filter even numbers and print them.

Loading...
Output:

Need Help?