C# LINQ (Language Integrated Query)
Objectives
- Introduction to LINQ?
- LINQ queries
- LINQ to Objects
Introduction to LINQ?
LINQ (Language Integrated Query) is a feature in C# that lets you query and manipulate data from different sources of data using one syntax.
It consists of a standard query operators range, that can be used for performing filtering, sorting, grouping as well as projection of data.
It provides an intuitive and coherent way of querying data from databases, XML, in-memory collections etc.
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);
}
}
}