C# LINQ (Language Integrated Query)

LINQ queries

These are expressions written in C#, which use the LINQ syntax to query and manipulate data.

While they look like SQL queries, LINQ queries deal with objects and collections in memory rather than database tables.

Example of a LINQ query to filter and project data from a collection:

                                                    
                                                    using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List numbers = new List { 1, 2, 3, 4, 5 };
        
        var query = from num in numbers
                    where num % 2 == 0
                    select num * num;

        foreach (var result in query)
        {
            Console.WriteLine(result);
        }
    }
}
                                                    
                                                

LINQ to Objects:

This is the name given to the LINQ provider that enables querying and manipulation of information stored in-memory collections for example arrays, lists or dictionaries.

There exist some standard query operators for objects and collections within it.

Example of using LINQ to Objects to query data from an array:

                                                    
                                                    using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        var query = from num in numbers
                    where num % 2 == 0
                    select num * num;

        foreach (var result in query)
        {
            Console.WriteLine(result);
        }
    }
}