LINQ
LINQ
LINQ stands for Language Integrated Query, a Microsoft .NET Framework that provides a
standardized way to query data from various data sources using a common syntax within
programming languages like C# or VB.
LINQ allows developers to write queries to retrieve, manipulate, and transform data from
different data sources, such as databases, collections, XML, and In-Memory objects.
Architecture of LINQ
The architecture of LINQ is 3-layered architecture. In which the topmost layer contains
language extension and the bottom layer contains data sources that generally object
implementing IEnumerable <T> or IQueryable <T> generic interfaces. The architecture of
the LINQ is as shown in the below image:
The main purpose behind creating LINQ is, before C# 3.0 we use for loop,
foreach loop, or delegates traverse a collection to find a specific object, but
the disadvantage of using these methods for finding an object is you need to
write a large sum of code to find an object which is more time-consuming and
make your program less readable. So to overcome these problems LINQ
introduced. Which perform the same operation in a few numbers of lines and
make your code more readable and also you can use the same code in other
programs.
It also provides full type checking at compile time, it helps us to detect the
error at the runtime, so that we can easily remove them.
LINQ is it is simple, well-ordered, and high-level language than SQL
You can also use LINQ with C# array and collections. It gives you a new
direction to solve the old problems in an effective manner.
With the help of LINQ you can easily work with any type of data source like
XML, SQL, Entities, objects, etc. A single query can work with any type of
database no need to learn different types of languages.
LINQ supports query expression, Implicitly typed variables, Object and
collection initializers, Anonymous types, Extension methods, and Lambda
expressions.
Query Expression
A Query is a set of instructions that describe what the data is to retrieve from a given data
source. And a Query Expression is a query, expressed in query syntax. A LINQ Query
Expression is also very similar to SQL. A LINQ Query Expression contains the following
three (3) clauses:
From
Where
Select
From: specifies the data source
Where: applies data filtration
Select: specifies the returned elements
Example:-
Example
Example
1. var num = 5;
2. var str="Rajeev";
3. var query = from s in StringArray
4. where s[0] == 'm'
5. select s;
Anonymous types
Anonymous types are class types that derive directly from an object and that cannot
be cast to any type except objects.
It is not different from any other reference type.
The complier provides a name for each anonymous type
. Anonymous types are typically used in the select clause of a query expression to
return a subset of properties from each object in the source sequence.
Anonymous types contains one or more public read-only properties.
The expression that is used to initialized a property cannot be null.
Example
Lambda Expression
A lambda expression is an anonymous function that we can use to create delegates or
expression tree types.
By using lambda expressions, we can write local functions that can be passed as
arguments or returned as the value of function calls
. Lambda expressions are particularly helpful for writing LINQ query expressions.
A lambda expression is an inline function that uses the => operator to separate input
parameters from the function body and can be converted at compile time to a delegate
or an expression tree
. In LINQ programming, you will encounter lambda expressions when you make
direct method calls to the standard query operators.
Example
a. Query Syntax
Definition: A syntax similar to SQL that allows you to write queries in a more
readable way.
Usage: Useful for complex queries that benefit from a structured format.
Example:
b. Method Syntax
Example:
a. Query Syntax
Definition: A syntax similar to SQL that allows you to write queries in a more
readable way.
Usage: Useful for complex queries that benefit from a structured format.
Example:
where n % 2 == 0
select n;
Console.WriteLine(num);
b. Method Syntax
Example
Console.WriteLine(num);
LINQ expression
For example, you can assign lambda expression to the isTeenAger variable of Func
type delegate, as shown below:
using System;
using System.Linq.Expressions;
//Invoke
bool result = isTeenAger(new Student(){ StudentID = 1, StudentName = "Steve", Age =
14});
Console.WriteLine(result);
}
}
Output ;- true
LinQ pattern
Explanation:
Program
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQExamples
};
// Example 1: Filtering
Output ;-
People with even ages:
Alice, Age: 30
Diana, Age: 18
Edward, Age: 22
Explanation:
The Select method transforms each element of a collection into a new form, defined by the
projection function.
It creates a new collection where each element is the result of applying the transformation to
the original element.
Useful when you want to create a new collection with a different type or shape (e.g.,
extracting specific properties from objects).
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQExamples
{
// Class representing a person
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
// Example 2: Projection
var names = people.Select(p => p.Name).ToList();
Console.WriteLine("\nNames of people:");
Console.WriteLine(string.Join(", ", names));
}
}
}
Output:-
Names of people:
Alice, Bob, Charlie, Diana, Edward
Explanation:
OrderBy sorts the elements of a collection in ascending order based on a specified key.
OrderByDescending does the same but in descending order.
The sorting is stable, meaning that elements that are equal in the sort key retain their original
order.
Essential for displaying data in a user-friendly format, such as sorting names alphabetically
or prices from low to high.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQExamples
{
// Class representing a person
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
// Example 3: Ordering
var sortedByAge = people.OrderBy(p => p.Age).ToList();
Console.WriteLine("\nPeople sorted by age:");
foreach (var person in sortedByAge)
{
Console.WriteLine($"{person.Name}, Age: {person.Age}");
}
}
}
}
Output ;-
The GroupBy method organizes a collection into groups based on a specified key.
Each group is represented as an IGrouping<TKey, TElement> where TKey is the type of the
key and TElement is the type of elements in the group.
Useful for categorizing data (e.g., grouping sales by product category or customers by
location).
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQExamples
{
public static void Main()
};
// Example 4: Grouping
Console.WriteLine($"Age: {group.Key}");
Console.WriteLine($" {person.Name}");
Output;-
People grouped by age:
Age: 30
Alice
Age: 25
Bob
Age: 35
Charlie
Age: 18
Diana
Age: 22
Edward
Explanation:
The Join method combines two collections based on a shared key, producing a new collection
of results.
It requires both collections to be related by a common key and produces pairs of elements
from each collection that match based on the key.
Commonly used when dealing with related datasets, like merging customer information with
their orders or invoices.
1. Inner Join
An inner join returns only the records that have matching values in both collections.
2. Left Outer Join
A left outer join returns all records from the left collection and the matched records from the
right collection. If there’s no match, the result is null on the right side.
A right outer join is not directly supported in LINQ syntax, but you can achieve it by
swapping the roles of the collections. It returns all records from the right collection and the
matched records from the left.
A full outer join returns all records when there is a match in either left or right collection.
This isn't directly supported in LINQ but can be simulated by combining left and right outer
joins.
using System;
using System.Collections.Generic;
using System.Linq;
namespace JoinExamples
class Program
};
};
// 1. Inner Join
}
6. Aggregating with Sum, Average, Min, Max, and Count
Explanation:
using System;
using System.Collections.Generic;
using System.Linq;
namespace AggregationExamples
class Program
};
// 1. Sum
// 2. Average
// 3. Min
// 4. Max
// 5. Count
}
}
Output:-
Average Age: 28
Maximum Age: 35
Explanation:
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQExamples
}
// Class representing an order
// Example 3: Ordering
Console.WriteLine("\nDistinct Ages:");
Console.WriteLine(age);
Output:-
Distinct Ages:
30
25
35
18
22
8. Combining Queries
Explanation:
LINQ allows you to chain multiple methods together to build complex queries in a
readable manner.
You can combine filtering, sorting, and projection in a single expression, which is
efficient and concise.
When you need to perform multiple operations on data sequentially, such as filtering,
then sorting, and finally selecting specific properties.
. using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQExamples
};
.ToList();
{
Console.WriteLine(name);
Output:-
Alice
Bob
Charlie
Diana
Edward