linq
  1. linq

LINQ - Language Integrated Query

LINQ stands for Language Integrated Query, which is a powerful technology that provides a consistent querying experience for data from different sources. LINQ allows querying and manipulating data from in-memory objects, XML documents, and relational databases using a common syntax.

Syntax

The basic syntax of LINQ to Objects is as follows:

var result = from variable in collection
             where condition
             select variable;

Example

Let's see a simple example using LINQ to select all even numbers from an array of integers.

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var evenNumbers = from number in numbers
                  where number % 2 == 0
                  select number;

foreach (var number in evenNumbers)
{
    Console.WriteLine(number);
}

Output

The output of the above code will be:

2
4
6
8
10

Explanation

In the above example, we have an array of integers named numbers. We are using LINQ to select all even numbers from the array. The LINQ query uses the where keyword to specify the condition that a number should be divided by 2 without remainder. The select keyword is used to select the numbers that satisfy the condition.

Use

LINQ is a versatile language feature that can be used in various scenarios. It is used to query and manipulate data from different sources, like in-memory objects, XML documents, and relational databases. It provides a common syntax for all data sources, which makes it easy to learn and write queries for programmers familiar with the syntax.

Important Points

  • LINQ queries are executed only when they are iterated or enumerated.
  • LINQ can be used to query and manipulate data from different sources, including in-memory objects, XML documents, and relational databases.
  • LINQ provides a fluent syntax for writing verbose queries.

Summary

In this article, we learned about Language Integrated Query (LINQ) in C#. We saw the basic syntax of LINQ and how it can be used to select data from arrays by applying filters based on conditions. We also learned about the use of LINQ in querying and manipulating data from different sources.

Published on:
LINQ Aggregation and Grouping