LINQ Basics

C# LINQ

LINQ (Language Integrated Query) in C# provides a streamlined and readable way to query collections of data. It integrates seamlessly with arrays, lists, XML, databases, and other collections, allowing developers to write expressive and concise code.

Key Components of LINQ

1. Query Syntax

Similar to SQL syntax.

Example:

int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers
                  where num % 2 == 0
                  select num;

foreach (var num in evenNumbers)
{
    Console.WriteLine(num); // Output: 2, 4
}

2. Method Syntax

Uses extension methods.

Example:

Common LINQ Methods

Method

Description

Example

Result

Where

Filters a sequence

numbers.Where(num => num > 2)

{ 3, 4, 5 }

Select

Projects values

numbers.Select(num => num * 2)

{ 2, 4, 6, 8, 10 }

OrderBy

Sorts in ascending order

numbers.OrderBy(num => num)

{ 1, 2, 3, 4, 5 }

OrderByDescending

Sorts in descending order

numbers.OrderByDescending(num => num)

{ 5, 4, 3, 2, 1 }

First

Returns the first element

numbers.First()

1

FirstOrDefault

Returns first element or default

numbers.FirstOrDefault(num => num > 5)

0 (default for int)

Sum

Calculates the sum of elements

numbers.Sum()

Sum of numbers

Max

Finds the maximum element

numbers.Max()

Maximum value

Min

Finds the minimum element

numbers.Min()

Minimum value

Average

Calculates the average

numbers.Average()

Average value

Count

Counts the number of elements

numbers.Count()

Number of elements

Combining LINQ Methods

Example:

Advanced Example with Classes

Let's use the provided Student and Product classes to illustrate LINQ in action:


Summary

  • LINQ Basics: Provides a way to query and manipulate collections using both query and method syntax.

  • Common Methods: Include Where, Select, OrderBy, First, Sum, Max, etc.

  • Examples: Demonstrate how to filter, sort, and aggregate data using LINQ.

LINQ in C# enhances code readability and efficiency, making data operations more intuitive and concise. It's an essential tool for any C# developer.