C# - Part II
Version 1.0 | 20th May 2023
LINQ
What is LINQ?
Microsoft introduced LINQ (Language Integrated Query) with .NET Framework 3.5 and C# 3.0, available in
the System.Linq namespace.
LINQ provides a common syntax that allows us to query the data from various data sources in a uniform manner.
That means using a single LINQ query, we can get or set the data from various data sources such as SQL Server
database, XML documents, ADO.NET Datasets, and any other in-memory objects such as Collections, Generics,
etc.
OOPs in C#
OOPs in C#
Why Should We Learn LINQ?
Let us understand why we should learn LINQ with an example. Suppose we are developing a .NET Application that
requires data from different sources.
For example
1.The application needs data from the SQL Server Database. So, as a developer, to access the data from the SQL
Server Database, we need to understand ADO.NET and SQL Server-specific syntaxes. We need to learn SQL
Syntax specific to Oracle Database if the database is Oracle.
2.The application also needs data from an XML Document. So, as a developer, to work with XML documents, we
need to understand XPath and XSLT queries.
3.The application also needs to manipulate the data (objects) in memory, such as List<Products>, List<Orders>,
etc. So, as a developer, we should also understand how to work with in-memory objects.
OOPs in C#
LINQ provides a Uniform Programming Model (i.e., Common Query Syntax), which allows us to work with
different data sources such as databases, XML Documents, in-memory objects, etc., but using a standard or, you
can say, unified coding style.
As a result, we are not required to learn different syntaxes to query different data sources.
Note: If you are working as a C# or VB.NET Developer (for developing Web, Windows, Mobile, Console, etc.),
then you should learn LINQ.
OOPs in C#
How Does LINQ Work?
Please look at the following diagram to understand how the LINQ works in the .NET Framework.
OOPs in C#
As shown in the above diagram, you can write the LINQ queries using any DOT NET Supported Programming
Language such as C#, VB.NET, J#, F#, etc.
The LINQ Provider is a software component that sits between the LINQ Queries and the Data Source.
The LINQ provider will convert the LINQ queries into a format that the underlying data source can understand.
For example, LINQ to SQL provider will convert the LINQ queries to SQL statements, which the SQL Server
database can understand.
Similarly, the LINQ to XML provider will convert the queries into a format the XML document can understand.
OOPs in C#
What are LINQ Providers?
LINQ (Language Integrated Query) providers are components that enable querying against a specific data
source using the LINQ syntax in .NET.
LINQ providers are components or libraries responsible for translating LINQ queries into a format that the
underlying data sources can execute.
The beauty of LINQ is its ability to provide a consistent querying experience across different types of data
sources, but it achieves this through using various LINQ providers.
Each provider is designed to work with a particular type of data source or a particular way of accessing data.
OOPs in C#
Here are some key points about LINQ providers:
•Translation of LINQ Queries: LINQ providers translate LINQ queries into the native query language of the
data source. For example, a LINQ provider for SQL Server translates LINQ queries into T-SQL queries.
•Different Providers for Different Data Sources: Different LINQ providers exist for different data sources.
Some common ones include:
• LINQ to Objects: Used for querying in-memory collections like arrays or lists.
• LINQ to SQL (DLinq): Used for querying SQL Server databases.
• LINQ to Entities (Entity Framework): Used for querying databases via the Entity Framework,
which supports multiple database types.
• LINQ to XML (XLinq): Used for querying XML documents.
OOPs in C#
•Custom Providers: Developers can create custom LINQ providers to enable LINQ querying over custom
data sources, like a proprietary database or a unique data format.
•Execution of Queries: The LINQ provider executes the query against the data source and returns the
results. This execution can involve translating the query into a different format, executing it, and then
materializing the results back into .NET objects.
•Performance Considerations: The efficiency of LINQ queries can depend heavily on the specific LINQ
provider used, as different providers have different ways of translating and executing queries.
OOPs in C#
Different Ways to Write LINQ Queries in C#:
LINQ queries can be written in two ways:
Query Syntax: It is similar to SQL and is often more readable for those familiar with SQL. It starts with a
from clause followed by a range variable and includes standard query operations like where, select,
group, join, etc.
var query = from c in customers where c.City == "London" select c.Name;
var query = from c in customers where c.City == "London“ select c.Name;
Method Syntax (Fluent Syntax): It uses extension methods and lambda expressions. It can be more concise and
is preferred when writing complex queries because it can be easier to read and compose.
var query = customers.Where(c => c.City == "London").Select(c => c.Name);
OOPs in C#
When to Use LINQ?
Knowing when to use LINQ is important for writing clean, efficient, and maintainable code
•Querying Collections: LINQ is ideal for querying collections like arrays, lists, or any other types that implement
IEnumerable. It simplifies the process of filtering, sorting, and grouping data.
•Database Operations: With LINQ to SQL or Entity Framework, you can perform database operations. LINQ
queries are automatically translated into SQL queries, making it easier to interact with databases without writing raw
SQL.
•Readability and Maintainability: LINQ queries often result in more readable and maintainable code compared to
traditional loops and conditional statements. The syntax is declarative, specifying what you want to do rather than
how to do it.
OOPs in C#
•Working with XML: LINQ to XML provides a simple and efficient way to handle XML documents. It allows you
to query, modify, and navigate XML data in a more readable and concise way.
•Joining Data Sources: If you need to join data from different sources (like different collections, databases, or
XML files), LINQ can be a powerful tool. It simplifies the syntax for joining and correlating data from multiple
sources.
•Aggregations and Calculations: When you need to perform calculations or aggregations (like sum, average,
min, max) on a collection of items, LINQ offers straightforward methods to accomplish these tasks.
•Converting Data Types: LINQ provides easy-to-use methods for converting one type of data into another,
such as converting an array to a list or vice versa.
OOPs in C#
What are the Advantages of using LINQ?
1.We don’t need to learn new query language syntaxes for different data sources as it provides common query
syntax to query different data sources.
2.Less code as compared to the traditional approach. That means by using LINQ, we can minimize our code.
3.It provides Compile-time error checking as well as intelligence support in Visual Studio. This powerful feature
helps us to avoid run-time errors.
4.LINQ provides many inbuilt methods that we can use to perform different operations such as filtering,
ordering, grouping, etc., which makes our work easy.
5.Its query can be reused.
OOPs in C#
The disadvantages of using LINQ are as follows:
1.Using LINQ, it isn’t easy to write complex queries like SQL.
2.LINQ doesn’t take full advantage of SQL features like a cached execution plan for the stored
procedure.
3.We will get the worst performance if we don’t write the queries properly.
4.If we make some changes to our queries, we need to recompile the application and redeploy the DLL to
the server.
OOPs in C#
Different Ways to Write LINQ Queries in C# with Examples
What are the different things required to write a LINQ Query?
 Data Source (In-Memory Objects, SQL Server, XML Document, etc)
 Query
 Execution of the Query
OOPs in C#
What is a Query?
A query is nothing but a set of instructions applied to a data source (i.e., In-Memory Objects, SQL Server, XML
Document, etc.) to perform certain operations (i.e., CRUD operations) and then tells the shape of the output from
that query.
That means the query is not responsible for what will be the output rather, it is responsible for the shape of the
output.
This also means what will return from that query, whether it will return a particular value, a particular list, or an
object. Each query is a combination of three things.
They are as follows:
1. Initialization (to work with a particular data source)
2. Condition (where, filter, sorting condition)
3. Selection (single selection, group selection, or joining)
OOPs in C#
What are the Different Ways to Write a LINQ Query?
In C#, LINQ (Language-Integrated Query) queries can be written in two primary ways: Query Syntax and Method
Syntax.
Both can be used to perform the same operations. Still, they have different styles, and some developers may
prefer one over the other based on the readability and complexity of the query.
We can write the LINQ query in three different ways. They are as follows.
 Query Syntax
 Method Syntax
 Mixed Syntax (Query + Method)
Note: From the performance point of view, there is no difference
between the above three approaches. So, which you need to use
totally depends on your personal preference. But the point that you
need to keep in mind is, behind the scenes, the LINQ queries written
using query syntax are translated into their lambda expressions
before they are compiled.
OOPs in C#
LINQ Query Syntax:
Query Syntax is more similar to SQL, providing a readable and declarative way of writing queries. Under the hood, it
gets translated into Method Syntax at compile time.
This is one of the easy ways to write complex LINQ queries in an easy and readable format. If you are familiar with
SQL Queries, it will be easy for you to write LINQ queries using this query syntax.
The syntax is given below.
OOPs in C#
Characteristics:
 Resembles SQL-like declarative style.
 It can be more readable, especially for those familiar with SQL.
 Not all operations can be expressed in Query Syntax; some require a switch to Method Syntax.
LINQ Method Syntax:
Method Syntax (also known as Fluent Syntax or Lambda Syntax) uses extension methods included in the
System.Linq namespace and can be chained together to perform complex queries.
It is similar to calling methods in a traditional object-oriented programming language. Method syntax has become
most popular nowadays for writing LINQ queries.
OOPs in C#
In this approach, the LINQ query is written using multiple methods by combining them with a dot (.), i.e.,
method chaining.
The Syntax is given below:
Characteristics:
 Utilizes lambda expressions.
 It can be more concise for complex queries.
 Offers slightly more methods and flexibility than Query Syntax.
 It can be easier to understand for those familiar with lambda expressions and functional programming.
OOPs in C#
LINQ Mixed Syntax:
You can also mix both syntaxes, although this is less common. This is the combination of both Query and
Method syntax. The syntax is given below.
Comparison Between Method and Query
Syntax:
•Interchangeability: Most queries can be written in
either syntax, and it often comes down to personal
or team preference.
•Performance: There is no performance difference
between the two, as Query Syntax is translated into
Method Syntax at compile time.
•Complexity: For more complex queries, Method
Syntax can be more powerful and flexible, but
Query Syntax can be more intuitive for simpler
queries or for those with a background in SQL.
OOPs in C#
Example Using
LINQ Query
Syntax in C#:
OOPs in C#
OOPs in C#
Example Using LINQ
Method Syntax in C#:
OOPs in C#
OOPs in C#
Example Using LINQ Mixed
Syntax in C#:
Let us change our
requirements. First, we
need to filter the list where
the value is greater than 5,
and then we need to
calculate the sum.
OOPs in C#
OOPs in C#
When should you use the LINQ Method and Query Syntax?
In the .NET framework, LINQ (Language Integrated Query) provides two main ways to write queries: Method
syntax and Query syntax.
Both syntaxes can be used to perform a wide range of operations, such as filtering, sorting, and grouping,
but there are some differences in how they are used and in their capabilities.
OOPs in C#
When should you use LINQ Method Syntax (Fluent Syntax)?
•For more complex queries, especially those involving multiple operations. Method syntax can be more concise
and easier to read for these types of queries.
•When you need to use lambda expressions for more control or complexity in the query.
•If you are comfortable with functional programming concepts since it’s similar to functional programming methods
in other languages.
•When the operations you need are not supported by query syntax (e.g., Zip, Aggregate).
OOPs in C#
When should you use LINQ Query Syntax (Comprehension Syntax)?
•For simpler queries. Query syntax can be more readable and resemble SQL, making it easier for those familiar
with SQL to understand.
•When you prefer a declarative programming style.
•If the query closely aligns with SQL syntax (e.g., selecting from a single collection).
OOPs in C#
IEnumerable and IQueryable in C# with Examples
Let us understand these two interfaces with example
OOPs in C#
In the above example, we use the var keyword to create the variable and store the result of the LINQ query.
So, let’s check what the type of variable is. To check this, just mouse over the pointer onto the QuerySynntax
variable, and you will see that the type is IEnumerable<int>, which is a generic type. So, it is important to
understand what is IEnumerable<T>.
So, in the above example, instead of writing the var keyword, you can also write IEnumerable<int>, and it should
work as expected, as shown in the below example.
Linq in C#
OOPs in C#
What is IEnumerable in C#?
IEnumerable in C# is an interface that defines one method, GetEnumerator, which returns an IEnumerator object.
This interface is found in the System.Collections namespace.
It is a key part of the .NET Framework and is used to iterate over a collection of objects. The following is the
definition of the IEnumerator interface
OOPs in C#
GetEnumerator Method:
This is the only method defined in the IEnumerable interface. It returns an IEnumerator object, which provides
the ability to iterate through the collection by exposing a Current property and MoveNext() and Reset() methods.
•Current: A property that gets the current element in the collection.
•MoveNext(): This advances the enumerator to the next element of the collection.
•Reset(): Sets the enumerator to its initial position, which is before the first element in the collection.
IEnumerable is typically used with a foreach loop in C#.
The foreach loop automatically uses the GetEnumerator method and the IEnumerator object to iterate over the
elements of the collection.
OOPs in C#
Key Characteristic of IEnumerator in C#:
•Purpose: It provides a simple iteration over a collection of a specified type. It’s primarily used for in-memory
collections like arrays, lists, etc.
•Execution: When you use LINQ methods on an IEnumerable, the query is executed in the client’s memory. This
means all the data is loaded into memory from the data source (like a database), and the operation is performed.
•Methods: The extension methods for IEnumerable are defined in the System.Linq.Enumerable class.
•Deferred Execution: It supports deferred execution, but the query logic is executed locally on the client side.
•Use Case: Best suited for working with in-memory data where the dataset is not too large.
OOPs in C#
Example to understand Ienumerable
with Complex Type using C#:
LINQ in C#
What is IQueryable in C#?
IQueryable in C# is an interface that is used to query data from a data source. It is part of the System.Linq
namespace and is a key component in LINQ (Language Integrated Query).
Unlike IEnumerable, which is used for iterating over in-memory collections, IQueryable is designed for querying
data sources where the query is not executed until the object is enumerated.
This is particularly useful for remote data sources, like databases, enabling efficient querying by allowing the
query to be executed on the server side.
The following is the definition of the IQueryable interface.
OOPs in C#
Here are the key aspects of IQueryable:
•Deferred Execution: IQueryable defers the execution of the query until the queryable object is actually iterated
over. This means the query is not executed when defined but when the results are required.
•Expression Trees: IQueryable queries are represented as expression trees. An expression tree is a data structure
that represents code in a tree-like format, where each node is an expression, such as a method call or a binary
operation. This allows the query to be translated into a format that can be understood by the data source, such as
SQL for a database.
•Query Providers: IQueryable relies on an implementation of the IQueryProvider interface to execute queries. The
provider translates the expression tree into a format that can be executed against the data source.
OOPs in C#
Key Characteristic of IQueryable in C#:
•Purpose: It is intended to query data from out-of-memory sources, like a database or web service. It is a powerful
feature for LINQ, SQL, and Entity Framework.
•Execution: The query logic is translated into a format suitable for the data source (like SQL for a relational
database). The query is executed on the server side, which can improve performance and reduce network traffic.
•Methods: The extension methods for IQueryable are defined in the System.Linq.Queryable class.
•Deferred Execution: Supports deferred execution, and the query is executed in the data source (like a database).
•Use Case: This is ideal for remote data sources, like databases, where you want to leverage server-side resources
and minimize data transfer.
LINQ in C#
Example to Understand
IQueryable<T> Interface in C#.
LINQ in C#
Key Differences Between IEnumerable and IQueryable in C#
•Execution Context: IEnumerable executes in the client memory, whereas IQueryable executes on the data
source.
•Suitability: IEnumerable is suitable for LINQ to Objects and working with in-memory data. IQueryable is
suitable for LINQ to SQL or Entity Framework to interact with databases.
•Performance: IQueryable can perform better for large data sets as it allows the database to optimize and filter
data.
Choosing Between IEnumerable and IQueryable in C#:
•Use IEnumerable when working with in-memory data collections where the data set is not excessively large.
•Use IQueryable when querying data from out-of-memory sources like databases, especially when dealing with
large data sets, to take advantage of server-side processing and optimizations.
LINQ in C#
Differences Between IEnumerable and IQueryable in C#
The IEnumerable and IQueryable in C# are used to hold a collection of data and also to perform data
manipulation operations such as filtering, ordering, grouping, etc., based on the business requirements.
This article will show you the difference between IEnumerable and IQueryable in C# with Examples. For a better
understanding, please have a look at the following image.
As you can see, IEnumerable<T> fetches the record from the database without applying the filter. But
IQueryable<T> fetches the record from the database by applying the filter.
LINQ in C#
LINQ in C#
Example to Understand the Differences Between IEnumerable and IQueryable in C#
In this demo, we will create a Console Application to retrieve the data from the SQL Server database using the
Entity Framework Database First approach.
We are going to fetch the following Student information from the Student table.
LINQ in C#
Create a new Console application. Once you create the Console Application, add the ADO.NET Entity Data
Model using the Database First Approach pointing to the above database.
Example to Understand the Use of IEnumerable in C#
Let us modify the Main method of the Program class as shown below.
In the example below, we are fetching the top 2 students from the Students table where the gender is male. But we
have split the LINQ query into two statements.
The first statement contains the where method, and the second statement contains the Take method. Then, using a
for each loop, we display the top 2 student information.
Further, to see what SQL Statement was generated and executed on the database by Entity Framework, we are
using DBContext.Database.Log = Console.Write statement that will log the SQL Script on the Console window.
LINQ in C#
LINQ in C#
Here, we create the LINQ Query using IEnumerable. With the above code in place, run the application and see the
output. You should get the following output.
As you can see in the above SQL Script, it will not use the TOP clause. So, here, it will fetch all the Male
Students from SQL Server to in-memory, and then it will filter the data in memory.
LINQ in C#
Example to Understand the Use of IQueryable in C#
Let us modify the Main method of the Program class as shown below to use IQueryable.
The following example does the same thing as the previous one, but here, we store the query in a variable of
IQueryable<Student> type.
For this, we are using the AsQueryable() method. We are also logging the generated SQL Statement on the Console
window.
LINQ in C#
LINQ in C#
As you can see in the above image, it includes the TOP (2) clause in the SQL Script and then fetches the data from
the database. That means the filtering is now happening on the database side. With this in mind, let us discuss the
differences between IEnumerable and IQueryable in C#.
LINQ in C#
IEnumerable vs. IQueryable in C#
IEnumerable and IQueryable are both interfaces in C# that are used for data manipulation and query operations,
but they serve different purposes and are used in different contexts.
Understanding their differences is important for efficient and effective data operations in C#.
Namespace:
 IEnumerable: It is defined in the System.Collections namespace.
 IQueryable: It is defined in the System.Linq namespace.
Purpose and Data Sources:
 IEnumerable: Primarily used for querying and manipulating in-memory collections, such as arrays,
lists, and IEnumerable-compatible collections. Designed for querying data that is already in memory.
 IQueryable: Used for querying data from external data sources that may not be in memory, such as
databases, web services, or remote data stores. Designed for querying data that resides outside of
the application’s memory.
LINQ in C#
Data Source:
 IEnumerable: It can be used with any in-memory data collection, like arrays, lists, etc.
 IQueryable: It is typically used for remote data sources like databases, especially with ORM frameworks
like Entity Framework.
Querying Capability:
 IEnumerable: It supports LINQ-to-Objects, meaning it can execute LINQ queries on in-memory collections.
 IQueryable: It supports LINQ-to-Entities, meaning it can translate LINQ queries into database-specific
query languages (like SQL for relational databases).
LINQ in C#
Execution Location:
 IEnumerable: Operations are executed in memory. All data is retrieved from the collection, and
subsequent operations are performed in memory.
 IQueryable: Operations are typically translated into a query language (e.g., SQL for databases) and
executed on the data source. This allows for server-side processing and optimization.
Lazy Evaluation:
 IEnumerable: Supports lazy evaluation. Operations are only executed when the collection is
enumerated (e.g., in a for each loop).
 IQueryable: Also supports lazy evaluation. Queries are not executed until you enumerate the results,
allowing for efficient resource use.
LINQ in C#
LINQ in C#
Choosing Between Them
1.Use IEnumerable for in-memory data collections or when dealing with small data sets.
2.Use IQueryable when querying large data sets or remote data sources like databases, especially when you need
efficient querying and data retrieval.
LINQ in C#
LINQ Extension Methods in C# with Examples
What are LINQ Extension Methods?
The LINQ’s standard query operators, such as select, where, etc., are implemented in the Enumerable class.
These methods are implemented as extension methods of the type IEnumerable<T> interface.
Let us understand this with an example. We have the following code in our Main method.
LINQ in C#
The above Where() method does not belong to the List<T> class, but still, we can call it as it belongs to
the List<T> class.
Why can it be called using the List<T> object? Let’s find out. If you go to the definition of the Where method, then
you will find the following definition.
As you can see in the signature, the where Where() method is implemented as an extension method on
the IEnumerable<T> interface, and we know List<T> implements the IEnumerable<T> interface.
This is the reason why we can call the Where() method using the List<T> object. With this in mind, let us
understand what extension methods are and how they are implemented in C#.
LINQ in C#
What are Extension Methods in C#?
According to MSDN, Extension Methods allow us to add methods to existing types without creating a new derived
type, recompiling, or modifying the original type.
In simple words, we can say that the Extension methods can be used as an approach to extending the functionality
of a class by adding new methods into the existing class if the source code of the class is not available or if we don’t
have any permission in making changes to the existing class.
The most important point you need to remember is that extension methods are the static methods of a static class,
but they will be called as if they were instance methods on the extended type.
LINQ in C#
When should you use extension methods in C#?
You need to use an extension method if any of the following conditions are true:
1.You need a method on an existing type, and you are not the owner of the source code of that type.
2.You need a method on an existing type; you do not own the source code of that type, but that type is an interface.
3.You need a method on an existing type, you do not own the source code, and that type is not an interface, but
adding the method creates undesired coupling.
Otherwise, you should go with the normal method of the actual type itself.
LINQ in C#
How do you implement extension methods in C#?
Let us understand this with an example. Our requirement is that we want to add a method in the built-in string class.
Let’s call this method GetWordCount(), which will count the word present in a string separated by a space.
For example, if the string is “Welcome to Dotnet Tutorials,” it should return the word count as 4.
The most important point is that we need to call this method on the String object, as shown below.
int wordCount = sentence.GetWordCount();
Note: We cannot define the GetWordCount() method directly in the string class as we do not own the string class.
The string class belongs to the System namespace, owned by the .NET framework. So, the alternative solution to
achieve this is to write a wrapper class, as shown below.
LINQ in C#
public class ExtensionHelper
{
public static int GetWordCount(string str)
{
if (!String.IsNullOrEmpty(str))
return str.Split(' ').Length;
return 0;
}
}
The above ExtensionHelper Wrapper class works fine, but the problem is that we cannot call the GetWordCount()
method using the string object, as shown below.
int wordCount = sentence.GetWordCount();
Instead, we need to call the GetWordCount() method, as shown below.
int wordCount = ExtensionHelper.GetWordCount(sentence);
LINQ in C#
How do you convert the above GetWordCount() method to an Extension Method of the String class?
Now, let’s convert the GetWordCount() method to an extension method on the String class.
So that we can able to call the GetWordCount() method using the following syntax.
int wordCount = sentence.GetWordCount();
To make the above GetWordCount() method an extension method, we need to make the following changes.
1. First, we need to make the ExtensionHelper class a static class.
2. Second, the type the method extends (i.e., string) should be passed as the first parameter preceding the “this
keyword to the GetWordCount() method.
With the above two changes in place, the GetWordCount() method becomes an extension method, and hence,
we can call the GetWordCount() method in the same way as we call an instance method of a class. The
complete example code is given below.
LINQ in C#
using System;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
string sentence = "Welcome to Dotnet Tutorials";
int wordCount = sentence.GetWordCount();
Console.WriteLine($"Count : {wordCount}");
Console.ReadKey();
}
}
public static class ExtensionHelper
{
public static int GetWordCount(this string str)
{
if (!String.IsNullOrEmpty(str))
return str.Split(' ').Length;
return 0;
}
}
}
LINQ in C#
LINQ in C#
That means it is also possible to call the LINQ extension methods such as select, where, etc., using the wrapper
class style syntax.
As all the LINQ extension methods are implemented in the Enumerable class, the syntax to call those methods
should look as shown below
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> EvenNumbers = Enumerable.Where(intList, n => n % 2 == 0);
foreach(var i in EvenNumbers ) Console.WriteLine(i); Console.ReadKey();
}
}
}
LINQ in C#
LINQ Extension Method in C#:
LINQ (Language Integrated Query) extension methods in C# are a set of methods provided by the System.Linq
namespace that extends the capabilities of collections (like arrays, lists, and other types implementing
IEnumerable<T>) by adding query functionality.
These methods enable querying collections using a SQL-like syntax directly in C#.
Here’s an overview of some commonly used LINQ extension methods:
Where: Filters a sequence based on a predicate.
var filteredResult = collection.Where(item => item.Property == someValue);
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ Operators in C#
What are LINQ Operators?
The LINQ Operators are nothing but a set of extension methods used to write the LINQ Query.
These LINQ extension methods provide many useful features we can apply to the data source.
Some of the features are filtering the data, sorting the data, grouping the data, etc.
What are the Categories of LINQ Operators?
LINQ (Language-Integrated Query) operators in C# provide a way to query and manipulate data from arrays,
enumerable classes, XML, relational databases, and third-party data sources.
The operators are divided into different categories based on their functionality:
LINQ in C#
Projection Operators:
These operators transform the elements of a sequence into a new form. Common projection operators include
Select and SelectMany.
 Select: Projects each element of a sequence into a new form.
 SelectMany: Projects each sequence element to an IEnumerable<T> and flattens the resulting
sequences into one sequence.
Filtering Operators:
These are used for filtering data. The most common restriction operator is Where which applies a predicate to each
element of a sequence and returns those that satisfy the condition.
 Where: Filters a sequence of values based on a predicate.
 OfType: Filters the elements of an array based on a specified type.
LINQ in C#
Partitioning Operators:
These operators divide a sequence into two parts and return one of them. Examples include Take, Skip,
TakeWhile, and SkipWhile.
 Take: Returns a specified number of contiguous elements from the start of a sequence.
 Skip: Bypasses a specified number of elements in a sequence and then returns the remaining
elements.
 TakeWhile: Returns elements from a sequence as long as a specified condition is true.
 SkipWhile: Bypasses elements in a sequence as long as a specified condition is true and then
returns the remaining elements.
LINQ in C#
Ordering Operators:
These operators arrange the elements of a sequence. Common ordering operators are OrderBy,
OrderByDescending, ThenBy, and ThenByDescending.
 OrderBy: Sorts the elements of a sequence in ascending order according to a key.
 OrderByDescending: Sorts the elements of a sequence in descending order according to a key.
 ThenBy: Performs a subsequent ordering of the elements in a sequence in ascending order.
 ThenByDescending: Performs a subsequent ordering of the elements in a sequence in descending order.
 Reverse: Inverts the order of the elements in a sequence.
LINQ in C#
Grouping Operators:
These operators group elements of a sequence based on a specified key value. The most notable grouping operator
is GroupBy.
 GroupBy: Groups the elements of a sequence according to a specified key selector function.
Join Operators:
These operators are used to combine elements from two or more sequences. Common join operators are Join and
GroupJoin.
 Join: Joins two sequences based on matching keys.
 GroupJoin: Groups elements from a sequence based on a key and joins them with elements from another
sequence.
LINQ in C#
Set Operators:
These operators perform mathematical set operations on sequences, such as Distinct, Union, Intersect, and Except.
 Distinct: Removes duplicate elements from a sequence.
 Union: Produces the set union of two sequences.
 Intersect: Produces the set intersection of two sequences.
 Except: Produces the set difference of two sequences.
LINQ in C#
Conversion Operators:
These are used to convert one type of sequence or collection to another. Examples include ToArray, ToList,
ToDictionary, and AsEnumerable.
 AsEnumerable: Casts an IEnumerable to an IEnumerable<T>.
 ToArray: Converts a sequence to an array.
 ToList: Converts a sequence to a List<T>.
 ToDictionary: Converts a sequence to a Dictionary<TKey, TValue> based on a key selector function.
LINQ in C#
Element Operators:
These operators return a single element from a sequence. Examples include First, FirstOrDefault, Last,
LastOrDefault, Single, SingleOrDefault, and ElementAt.
 First: Returns the first element of a sequence.
 FirstOrDefault: Returns the first element of a sequence or a default value if no element is found.
 Last: Returns the last element of a sequence.
 LastOrDefault: Returns the last element of a sequence or a default value if no element is found.
 Single: Returns the only element of a sequence and throws an exception if there is not exactly one element
in the sequence.
 SingleOrDefault: Returns the only element of a sequence or a default value if the sequence is empty; this
method throws an exception if there is more than one element in the sequence.
 ElementAt: Returns the element at a specified index in a sequence.
 ElementAtOrDefault: Returns the element at a specified index in a sequence or a default value if the index
is out of range.
LINQ in C#
Quantifier Operators:
These operators return a Boolean value indicating whether all or any of the elements of a sequence satisfy a
condition. Examples are All, Any, and Contains.
 Any: Determines whether any element of a sequence satisfies a condition.
 All: Determines whether all elements of a sequence satisfy a condition.
 Contains: Determines whether a sequence contains a specified element.
Equality Operators:
These operators are used to compare sequences for equality. An example is SequenceEqual.
 SequenceEqual: Determines whether two sequences are equal by comparing the elements by using the
default equality comparer for their type.
LINQ in C#
Aggregate Operators:
These operators perform a calculation on a sequence and return a single value. Examples include Count, Sum,
Min, Max, Average, and Aggregate.
 Count: Counts the elements in a sequence.
 LongCount: Counts the elements in a sequence, returning the count as a long.
 Sum: Computes the sum of a sequence of numeric values.
 Min: Returns the minimum value in a sequence.
 Max: Returns the maximum value in a sequence.
 Average: Computes the average of a sequence of numeric values.
 Aggregate: Applies an accumulator function over a sequence.
LINQ in C#
Generation Operators:
These operators are used to create a new sequence of values. Examples include Range, Repeat, and Empty.
 Empty: Returns an empty IEnumerable<T> with the specified type argument.
 Repeat: Generates a sequence that contains one repeated value.
 Range: Generates a sequence of integral numbers within a specified range.
Special Operators:
 Concatenation Operators: These operators concatenate two sequences. The primary operator in this
category is Concat.
 DefaultIfEmpty Operators: This operator returns the elements of the specified sequence or the type
parameter’s default value in a singleton collection if the sequence is empty.
LINQ in C#
LINQ Select Operator/Method in C# with Examples
Projection Operators:
These operators transform the elements of a sequence into a new form. Common projection operators include
 Select
 SelectMany.
LINQ Select Operator/Method using C#:
Create a console application named LINQDemo (you can give any meaningful name). Then, add a new class
file with the name Employee.cs. Once you add the Employee.cs class file, copy and paste the following code.
LINQ in C#
LINQ in C#
Select all the Employee data from the data source using both the LINQ Method and Query Syntax.
Please look at the following image, which shows Query and Method Syntax to fetch all the Employees.
The following image is self-explained.
You need to remember that it is not executed when we form the query.
When we call the ToList() Method, Sum() Method, etc., or use the Query variable within a for-each loop, only the
Query will be executed.
LINQ in C#
LINQ in C#
LINQ in C#
using System;
using System.Collections.Generic;
using System.Linq;
public class HelloWorld
{
public static void Main(string[] args)
{
//Using Query Syntax
List<Employee> basicQuery = (from emp in Employee.GetEmployees()
select emp).ToList();
foreach (Employee emp in basicQuery)
{
Console.WriteLine($"ID : {emp.ID} Name : {emp.FirstName} {emp.LastName}");
}
//Using Method Syntax
IEnumerable<Employee> basicMethod = Employee.GetEmployees().ToList();
foreach (Employee emp in basicMethod)
{
Console.WriteLine($"ID : {emp.ID} Name : {emp.FirstName} {emp.LastName}");
}
Console.ReadKey();
}
}
LINQ in C#
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Salary { get; set; }
public static List<Employee> GetEmployees()
{
List<Employee> employees = new List<Employee>
{
new Employee {ID = 101, FirstName = "Preety", LastName = "Tiwary", Salary = 60000 },
new Employee {ID = 102, FirstName = "Priyanka", LastName = "Dewangan", Salary = 70000 },
new Employee {ID = 103, FirstName = "Hina", LastName = "Sharma", Salary = 80000 },
new Employee {ID = 104, FirstName = "Anurag", LastName = "Mohanty", Salary = 90000 },
new Employee {ID = 105, FirstName = "Sambit", LastName = "Satapathy", Salary = 100000 },
new Employee {ID = 106, FirstName = "Sushanta", LastName = "Jena", Salary = 160000 }
};
return employees; }
}
LINQ in C#
LINQ in C#
How do you Select a Single Property using LINQ Select Operator or Method in C#?
Note: In the Query Syntax, the data type of the basicPropQuery variable is List<int>. This is because of the
ToList() method applied to the Query Syntax. And because of this ToList() method, the query is executed at that
point only.
But in the case of Method Syntax, we have not applied the ToList() method, which is why the data type of
the basicPropMethod variable is of IEnumerable<int> type. And more importantly, at that point, the query is
generated but not executed. When we use the basicPropMethod variable within the for-each loop, the query will
be executed at that time.
LINQ in C#
LINQ in C#
How Does It Work Internally?
 Iteration: The Select operator iterates over each element in the source sequence.
 Transformation: For each element, it applies the transformation logic defined in the lambda expression.
 Result: It produces a new sequence where each element is the result of the applied transformation on the
corresponding element from the source sequence.
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#
LINQ in C#

SQL ttrain wrwrwrw wwrw wwrrrwrwrwrwwrwr.pptx

  • 1.
    C# - PartII Version 1.0 | 20th May 2023
  • 2.
    LINQ What is LINQ? Microsoftintroduced LINQ (Language Integrated Query) with .NET Framework 3.5 and C# 3.0, available in the System.Linq namespace. LINQ provides a common syntax that allows us to query the data from various data sources in a uniform manner. That means using a single LINQ query, we can get or set the data from various data sources such as SQL Server database, XML documents, ADO.NET Datasets, and any other in-memory objects such as Collections, Generics, etc.
  • 3.
  • 4.
    OOPs in C# WhyShould We Learn LINQ? Let us understand why we should learn LINQ with an example. Suppose we are developing a .NET Application that requires data from different sources. For example 1.The application needs data from the SQL Server Database. So, as a developer, to access the data from the SQL Server Database, we need to understand ADO.NET and SQL Server-specific syntaxes. We need to learn SQL Syntax specific to Oracle Database if the database is Oracle. 2.The application also needs data from an XML Document. So, as a developer, to work with XML documents, we need to understand XPath and XSLT queries. 3.The application also needs to manipulate the data (objects) in memory, such as List<Products>, List<Orders>, etc. So, as a developer, we should also understand how to work with in-memory objects.
  • 5.
    OOPs in C# LINQprovides a Uniform Programming Model (i.e., Common Query Syntax), which allows us to work with different data sources such as databases, XML Documents, in-memory objects, etc., but using a standard or, you can say, unified coding style. As a result, we are not required to learn different syntaxes to query different data sources. Note: If you are working as a C# or VB.NET Developer (for developing Web, Windows, Mobile, Console, etc.), then you should learn LINQ.
  • 6.
    OOPs in C# HowDoes LINQ Work? Please look at the following diagram to understand how the LINQ works in the .NET Framework.
  • 7.
    OOPs in C# Asshown in the above diagram, you can write the LINQ queries using any DOT NET Supported Programming Language such as C#, VB.NET, J#, F#, etc. The LINQ Provider is a software component that sits between the LINQ Queries and the Data Source. The LINQ provider will convert the LINQ queries into a format that the underlying data source can understand. For example, LINQ to SQL provider will convert the LINQ queries to SQL statements, which the SQL Server database can understand. Similarly, the LINQ to XML provider will convert the queries into a format the XML document can understand.
  • 8.
    OOPs in C# Whatare LINQ Providers? LINQ (Language Integrated Query) providers are components that enable querying against a specific data source using the LINQ syntax in .NET. LINQ providers are components or libraries responsible for translating LINQ queries into a format that the underlying data sources can execute. The beauty of LINQ is its ability to provide a consistent querying experience across different types of data sources, but it achieves this through using various LINQ providers. Each provider is designed to work with a particular type of data source or a particular way of accessing data.
  • 9.
    OOPs in C# Hereare some key points about LINQ providers: •Translation of LINQ Queries: LINQ providers translate LINQ queries into the native query language of the data source. For example, a LINQ provider for SQL Server translates LINQ queries into T-SQL queries. •Different Providers for Different Data Sources: Different LINQ providers exist for different data sources. Some common ones include: • LINQ to Objects: Used for querying in-memory collections like arrays or lists. • LINQ to SQL (DLinq): Used for querying SQL Server databases. • LINQ to Entities (Entity Framework): Used for querying databases via the Entity Framework, which supports multiple database types. • LINQ to XML (XLinq): Used for querying XML documents.
  • 10.
    OOPs in C# •CustomProviders: Developers can create custom LINQ providers to enable LINQ querying over custom data sources, like a proprietary database or a unique data format. •Execution of Queries: The LINQ provider executes the query against the data source and returns the results. This execution can involve translating the query into a different format, executing it, and then materializing the results back into .NET objects. •Performance Considerations: The efficiency of LINQ queries can depend heavily on the specific LINQ provider used, as different providers have different ways of translating and executing queries.
  • 11.
    OOPs in C# DifferentWays to Write LINQ Queries in C#: LINQ queries can be written in two ways: Query Syntax: It is similar to SQL and is often more readable for those familiar with SQL. It starts with a from clause followed by a range variable and includes standard query operations like where, select, group, join, etc. var query = from c in customers where c.City == "London" select c.Name; var query = from c in customers where c.City == "London“ select c.Name; Method Syntax (Fluent Syntax): It uses extension methods and lambda expressions. It can be more concise and is preferred when writing complex queries because it can be easier to read and compose. var query = customers.Where(c => c.City == "London").Select(c => c.Name);
  • 12.
    OOPs in C# Whento Use LINQ? Knowing when to use LINQ is important for writing clean, efficient, and maintainable code •Querying Collections: LINQ is ideal for querying collections like arrays, lists, or any other types that implement IEnumerable. It simplifies the process of filtering, sorting, and grouping data. •Database Operations: With LINQ to SQL or Entity Framework, you can perform database operations. LINQ queries are automatically translated into SQL queries, making it easier to interact with databases without writing raw SQL. •Readability and Maintainability: LINQ queries often result in more readable and maintainable code compared to traditional loops and conditional statements. The syntax is declarative, specifying what you want to do rather than how to do it.
  • 13.
    OOPs in C# •Workingwith XML: LINQ to XML provides a simple and efficient way to handle XML documents. It allows you to query, modify, and navigate XML data in a more readable and concise way. •Joining Data Sources: If you need to join data from different sources (like different collections, databases, or XML files), LINQ can be a powerful tool. It simplifies the syntax for joining and correlating data from multiple sources. •Aggregations and Calculations: When you need to perform calculations or aggregations (like sum, average, min, max) on a collection of items, LINQ offers straightforward methods to accomplish these tasks. •Converting Data Types: LINQ provides easy-to-use methods for converting one type of data into another, such as converting an array to a list or vice versa.
  • 14.
    OOPs in C# Whatare the Advantages of using LINQ? 1.We don’t need to learn new query language syntaxes for different data sources as it provides common query syntax to query different data sources. 2.Less code as compared to the traditional approach. That means by using LINQ, we can minimize our code. 3.It provides Compile-time error checking as well as intelligence support in Visual Studio. This powerful feature helps us to avoid run-time errors. 4.LINQ provides many inbuilt methods that we can use to perform different operations such as filtering, ordering, grouping, etc., which makes our work easy. 5.Its query can be reused.
  • 15.
    OOPs in C# Thedisadvantages of using LINQ are as follows: 1.Using LINQ, it isn’t easy to write complex queries like SQL. 2.LINQ doesn’t take full advantage of SQL features like a cached execution plan for the stored procedure. 3.We will get the worst performance if we don’t write the queries properly. 4.If we make some changes to our queries, we need to recompile the application and redeploy the DLL to the server.
  • 16.
    OOPs in C# DifferentWays to Write LINQ Queries in C# with Examples What are the different things required to write a LINQ Query?  Data Source (In-Memory Objects, SQL Server, XML Document, etc)  Query  Execution of the Query
  • 17.
    OOPs in C# Whatis a Query? A query is nothing but a set of instructions applied to a data source (i.e., In-Memory Objects, SQL Server, XML Document, etc.) to perform certain operations (i.e., CRUD operations) and then tells the shape of the output from that query. That means the query is not responsible for what will be the output rather, it is responsible for the shape of the output. This also means what will return from that query, whether it will return a particular value, a particular list, or an object. Each query is a combination of three things. They are as follows: 1. Initialization (to work with a particular data source) 2. Condition (where, filter, sorting condition) 3. Selection (single selection, group selection, or joining)
  • 18.
    OOPs in C# Whatare the Different Ways to Write a LINQ Query? In C#, LINQ (Language-Integrated Query) queries can be written in two primary ways: Query Syntax and Method Syntax. Both can be used to perform the same operations. Still, they have different styles, and some developers may prefer one over the other based on the readability and complexity of the query. We can write the LINQ query in three different ways. They are as follows.  Query Syntax  Method Syntax  Mixed Syntax (Query + Method) Note: From the performance point of view, there is no difference between the above three approaches. So, which you need to use totally depends on your personal preference. But the point that you need to keep in mind is, behind the scenes, the LINQ queries written using query syntax are translated into their lambda expressions before they are compiled.
  • 19.
    OOPs in C# LINQQuery Syntax: Query Syntax is more similar to SQL, providing a readable and declarative way of writing queries. Under the hood, it gets translated into Method Syntax at compile time. This is one of the easy ways to write complex LINQ queries in an easy and readable format. If you are familiar with SQL Queries, it will be easy for you to write LINQ queries using this query syntax. The syntax is given below.
  • 20.
    OOPs in C# Characteristics: Resembles SQL-like declarative style.  It can be more readable, especially for those familiar with SQL.  Not all operations can be expressed in Query Syntax; some require a switch to Method Syntax. LINQ Method Syntax: Method Syntax (also known as Fluent Syntax or Lambda Syntax) uses extension methods included in the System.Linq namespace and can be chained together to perform complex queries. It is similar to calling methods in a traditional object-oriented programming language. Method syntax has become most popular nowadays for writing LINQ queries.
  • 21.
    OOPs in C# Inthis approach, the LINQ query is written using multiple methods by combining them with a dot (.), i.e., method chaining. The Syntax is given below: Characteristics:  Utilizes lambda expressions.  It can be more concise for complex queries.  Offers slightly more methods and flexibility than Query Syntax.  It can be easier to understand for those familiar with lambda expressions and functional programming.
  • 22.
    OOPs in C# LINQMixed Syntax: You can also mix both syntaxes, although this is less common. This is the combination of both Query and Method syntax. The syntax is given below. Comparison Between Method and Query Syntax: •Interchangeability: Most queries can be written in either syntax, and it often comes down to personal or team preference. •Performance: There is no performance difference between the two, as Query Syntax is translated into Method Syntax at compile time. •Complexity: For more complex queries, Method Syntax can be more powerful and flexible, but Query Syntax can be more intuitive for simpler queries or for those with a background in SQL.
  • 23.
    OOPs in C# ExampleUsing LINQ Query Syntax in C#:
  • 24.
  • 25.
    OOPs in C# ExampleUsing LINQ Method Syntax in C#:
  • 26.
  • 27.
    OOPs in C# ExampleUsing LINQ Mixed Syntax in C#: Let us change our requirements. First, we need to filter the list where the value is greater than 5, and then we need to calculate the sum.
  • 28.
  • 29.
    OOPs in C# Whenshould you use the LINQ Method and Query Syntax? In the .NET framework, LINQ (Language Integrated Query) provides two main ways to write queries: Method syntax and Query syntax. Both syntaxes can be used to perform a wide range of operations, such as filtering, sorting, and grouping, but there are some differences in how they are used and in their capabilities.
  • 30.
    OOPs in C# Whenshould you use LINQ Method Syntax (Fluent Syntax)? •For more complex queries, especially those involving multiple operations. Method syntax can be more concise and easier to read for these types of queries. •When you need to use lambda expressions for more control or complexity in the query. •If you are comfortable with functional programming concepts since it’s similar to functional programming methods in other languages. •When the operations you need are not supported by query syntax (e.g., Zip, Aggregate).
  • 31.
    OOPs in C# Whenshould you use LINQ Query Syntax (Comprehension Syntax)? •For simpler queries. Query syntax can be more readable and resemble SQL, making it easier for those familiar with SQL to understand. •When you prefer a declarative programming style. •If the query closely aligns with SQL syntax (e.g., selecting from a single collection).
  • 32.
    OOPs in C# IEnumerableand IQueryable in C# with Examples Let us understand these two interfaces with example
  • 33.
    OOPs in C# Inthe above example, we use the var keyword to create the variable and store the result of the LINQ query. So, let’s check what the type of variable is. To check this, just mouse over the pointer onto the QuerySynntax variable, and you will see that the type is IEnumerable<int>, which is a generic type. So, it is important to understand what is IEnumerable<T>. So, in the above example, instead of writing the var keyword, you can also write IEnumerable<int>, and it should work as expected, as shown in the below example.
  • 34.
  • 35.
    OOPs in C# Whatis IEnumerable in C#? IEnumerable in C# is an interface that defines one method, GetEnumerator, which returns an IEnumerator object. This interface is found in the System.Collections namespace. It is a key part of the .NET Framework and is used to iterate over a collection of objects. The following is the definition of the IEnumerator interface
  • 36.
    OOPs in C# GetEnumeratorMethod: This is the only method defined in the IEnumerable interface. It returns an IEnumerator object, which provides the ability to iterate through the collection by exposing a Current property and MoveNext() and Reset() methods. •Current: A property that gets the current element in the collection. •MoveNext(): This advances the enumerator to the next element of the collection. •Reset(): Sets the enumerator to its initial position, which is before the first element in the collection. IEnumerable is typically used with a foreach loop in C#. The foreach loop automatically uses the GetEnumerator method and the IEnumerator object to iterate over the elements of the collection.
  • 37.
    OOPs in C# KeyCharacteristic of IEnumerator in C#: •Purpose: It provides a simple iteration over a collection of a specified type. It’s primarily used for in-memory collections like arrays, lists, etc. •Execution: When you use LINQ methods on an IEnumerable, the query is executed in the client’s memory. This means all the data is loaded into memory from the data source (like a database), and the operation is performed. •Methods: The extension methods for IEnumerable are defined in the System.Linq.Enumerable class. •Deferred Execution: It supports deferred execution, but the query logic is executed locally on the client side. •Use Case: Best suited for working with in-memory data where the dataset is not too large.
  • 38.
    OOPs in C# Exampleto understand Ienumerable with Complex Type using C#:
  • 39.
    LINQ in C# Whatis IQueryable in C#? IQueryable in C# is an interface that is used to query data from a data source. It is part of the System.Linq namespace and is a key component in LINQ (Language Integrated Query). Unlike IEnumerable, which is used for iterating over in-memory collections, IQueryable is designed for querying data sources where the query is not executed until the object is enumerated. This is particularly useful for remote data sources, like databases, enabling efficient querying by allowing the query to be executed on the server side. The following is the definition of the IQueryable interface.
  • 40.
    OOPs in C# Hereare the key aspects of IQueryable: •Deferred Execution: IQueryable defers the execution of the query until the queryable object is actually iterated over. This means the query is not executed when defined but when the results are required. •Expression Trees: IQueryable queries are represented as expression trees. An expression tree is a data structure that represents code in a tree-like format, where each node is an expression, such as a method call or a binary operation. This allows the query to be translated into a format that can be understood by the data source, such as SQL for a database. •Query Providers: IQueryable relies on an implementation of the IQueryProvider interface to execute queries. The provider translates the expression tree into a format that can be executed against the data source.
  • 41.
    OOPs in C# KeyCharacteristic of IQueryable in C#: •Purpose: It is intended to query data from out-of-memory sources, like a database or web service. It is a powerful feature for LINQ, SQL, and Entity Framework. •Execution: The query logic is translated into a format suitable for the data source (like SQL for a relational database). The query is executed on the server side, which can improve performance and reduce network traffic. •Methods: The extension methods for IQueryable are defined in the System.Linq.Queryable class. •Deferred Execution: Supports deferred execution, and the query is executed in the data source (like a database). •Use Case: This is ideal for remote data sources, like databases, where you want to leverage server-side resources and minimize data transfer.
  • 42.
    LINQ in C# Exampleto Understand IQueryable<T> Interface in C#.
  • 43.
    LINQ in C# KeyDifferences Between IEnumerable and IQueryable in C# •Execution Context: IEnumerable executes in the client memory, whereas IQueryable executes on the data source. •Suitability: IEnumerable is suitable for LINQ to Objects and working with in-memory data. IQueryable is suitable for LINQ to SQL or Entity Framework to interact with databases. •Performance: IQueryable can perform better for large data sets as it allows the database to optimize and filter data. Choosing Between IEnumerable and IQueryable in C#: •Use IEnumerable when working with in-memory data collections where the data set is not excessively large. •Use IQueryable when querying data from out-of-memory sources like databases, especially when dealing with large data sets, to take advantage of server-side processing and optimizations.
  • 44.
    LINQ in C# DifferencesBetween IEnumerable and IQueryable in C# The IEnumerable and IQueryable in C# are used to hold a collection of data and also to perform data manipulation operations such as filtering, ordering, grouping, etc., based on the business requirements. This article will show you the difference between IEnumerable and IQueryable in C# with Examples. For a better understanding, please have a look at the following image. As you can see, IEnumerable<T> fetches the record from the database without applying the filter. But IQueryable<T> fetches the record from the database by applying the filter.
  • 45.
  • 46.
    LINQ in C# Exampleto Understand the Differences Between IEnumerable and IQueryable in C# In this demo, we will create a Console Application to retrieve the data from the SQL Server database using the Entity Framework Database First approach. We are going to fetch the following Student information from the Student table.
  • 47.
    LINQ in C# Createa new Console application. Once you create the Console Application, add the ADO.NET Entity Data Model using the Database First Approach pointing to the above database. Example to Understand the Use of IEnumerable in C# Let us modify the Main method of the Program class as shown below. In the example below, we are fetching the top 2 students from the Students table where the gender is male. But we have split the LINQ query into two statements. The first statement contains the where method, and the second statement contains the Take method. Then, using a for each loop, we display the top 2 student information. Further, to see what SQL Statement was generated and executed on the database by Entity Framework, we are using DBContext.Database.Log = Console.Write statement that will log the SQL Script on the Console window.
  • 48.
  • 49.
    LINQ in C# Here,we create the LINQ Query using IEnumerable. With the above code in place, run the application and see the output. You should get the following output. As you can see in the above SQL Script, it will not use the TOP clause. So, here, it will fetch all the Male Students from SQL Server to in-memory, and then it will filter the data in memory.
  • 50.
    LINQ in C# Exampleto Understand the Use of IQueryable in C# Let us modify the Main method of the Program class as shown below to use IQueryable. The following example does the same thing as the previous one, but here, we store the query in a variable of IQueryable<Student> type. For this, we are using the AsQueryable() method. We are also logging the generated SQL Statement on the Console window.
  • 51.
  • 52.
    LINQ in C# Asyou can see in the above image, it includes the TOP (2) clause in the SQL Script and then fetches the data from the database. That means the filtering is now happening on the database side. With this in mind, let us discuss the differences between IEnumerable and IQueryable in C#.
  • 53.
    LINQ in C# IEnumerablevs. IQueryable in C# IEnumerable and IQueryable are both interfaces in C# that are used for data manipulation and query operations, but they serve different purposes and are used in different contexts. Understanding their differences is important for efficient and effective data operations in C#. Namespace:  IEnumerable: It is defined in the System.Collections namespace.  IQueryable: It is defined in the System.Linq namespace. Purpose and Data Sources:  IEnumerable: Primarily used for querying and manipulating in-memory collections, such as arrays, lists, and IEnumerable-compatible collections. Designed for querying data that is already in memory.  IQueryable: Used for querying data from external data sources that may not be in memory, such as databases, web services, or remote data stores. Designed for querying data that resides outside of the application’s memory.
  • 54.
    LINQ in C# DataSource:  IEnumerable: It can be used with any in-memory data collection, like arrays, lists, etc.  IQueryable: It is typically used for remote data sources like databases, especially with ORM frameworks like Entity Framework. Querying Capability:  IEnumerable: It supports LINQ-to-Objects, meaning it can execute LINQ queries on in-memory collections.  IQueryable: It supports LINQ-to-Entities, meaning it can translate LINQ queries into database-specific query languages (like SQL for relational databases).
  • 55.
    LINQ in C# ExecutionLocation:  IEnumerable: Operations are executed in memory. All data is retrieved from the collection, and subsequent operations are performed in memory.  IQueryable: Operations are typically translated into a query language (e.g., SQL for databases) and executed on the data source. This allows for server-side processing and optimization. Lazy Evaluation:  IEnumerable: Supports lazy evaluation. Operations are only executed when the collection is enumerated (e.g., in a for each loop).  IQueryable: Also supports lazy evaluation. Queries are not executed until you enumerate the results, allowing for efficient resource use.
  • 56.
  • 57.
    LINQ in C# ChoosingBetween Them 1.Use IEnumerable for in-memory data collections or when dealing with small data sets. 2.Use IQueryable when querying large data sets or remote data sources like databases, especially when you need efficient querying and data retrieval.
  • 58.
    LINQ in C# LINQExtension Methods in C# with Examples What are LINQ Extension Methods? The LINQ’s standard query operators, such as select, where, etc., are implemented in the Enumerable class. These methods are implemented as extension methods of the type IEnumerable<T> interface. Let us understand this with an example. We have the following code in our Main method.
  • 59.
    LINQ in C# Theabove Where() method does not belong to the List<T> class, but still, we can call it as it belongs to the List<T> class. Why can it be called using the List<T> object? Let’s find out. If you go to the definition of the Where method, then you will find the following definition. As you can see in the signature, the where Where() method is implemented as an extension method on the IEnumerable<T> interface, and we know List<T> implements the IEnumerable<T> interface. This is the reason why we can call the Where() method using the List<T> object. With this in mind, let us understand what extension methods are and how they are implemented in C#.
  • 60.
    LINQ in C# Whatare Extension Methods in C#? According to MSDN, Extension Methods allow us to add methods to existing types without creating a new derived type, recompiling, or modifying the original type. In simple words, we can say that the Extension methods can be used as an approach to extending the functionality of a class by adding new methods into the existing class if the source code of the class is not available or if we don’t have any permission in making changes to the existing class. The most important point you need to remember is that extension methods are the static methods of a static class, but they will be called as if they were instance methods on the extended type.
  • 61.
    LINQ in C# Whenshould you use extension methods in C#? You need to use an extension method if any of the following conditions are true: 1.You need a method on an existing type, and you are not the owner of the source code of that type. 2.You need a method on an existing type; you do not own the source code of that type, but that type is an interface. 3.You need a method on an existing type, you do not own the source code, and that type is not an interface, but adding the method creates undesired coupling. Otherwise, you should go with the normal method of the actual type itself.
  • 62.
    LINQ in C# Howdo you implement extension methods in C#? Let us understand this with an example. Our requirement is that we want to add a method in the built-in string class. Let’s call this method GetWordCount(), which will count the word present in a string separated by a space. For example, if the string is “Welcome to Dotnet Tutorials,” it should return the word count as 4. The most important point is that we need to call this method on the String object, as shown below. int wordCount = sentence.GetWordCount(); Note: We cannot define the GetWordCount() method directly in the string class as we do not own the string class. The string class belongs to the System namespace, owned by the .NET framework. So, the alternative solution to achieve this is to write a wrapper class, as shown below.
  • 63.
    LINQ in C# publicclass ExtensionHelper { public static int GetWordCount(string str) { if (!String.IsNullOrEmpty(str)) return str.Split(' ').Length; return 0; } } The above ExtensionHelper Wrapper class works fine, but the problem is that we cannot call the GetWordCount() method using the string object, as shown below. int wordCount = sentence.GetWordCount(); Instead, we need to call the GetWordCount() method, as shown below. int wordCount = ExtensionHelper.GetWordCount(sentence);
  • 64.
    LINQ in C# Howdo you convert the above GetWordCount() method to an Extension Method of the String class? Now, let’s convert the GetWordCount() method to an extension method on the String class. So that we can able to call the GetWordCount() method using the following syntax. int wordCount = sentence.GetWordCount(); To make the above GetWordCount() method an extension method, we need to make the following changes. 1. First, we need to make the ExtensionHelper class a static class. 2. Second, the type the method extends (i.e., string) should be passed as the first parameter preceding the “this keyword to the GetWordCount() method. With the above two changes in place, the GetWordCount() method becomes an extension method, and hence, we can call the GetWordCount() method in the same way as we call an instance method of a class. The complete example code is given below.
  • 65.
    LINQ in C# usingSystem; namespace LINQDemo { class Program { static void Main(string[] args) { string sentence = "Welcome to Dotnet Tutorials"; int wordCount = sentence.GetWordCount(); Console.WriteLine($"Count : {wordCount}"); Console.ReadKey(); } } public static class ExtensionHelper { public static int GetWordCount(this string str) { if (!String.IsNullOrEmpty(str)) return str.Split(' ').Length; return 0; } } }
  • 66.
  • 67.
    LINQ in C# Thatmeans it is also possible to call the LINQ extension methods such as select, where, etc., using the wrapper class style syntax. As all the LINQ extension methods are implemented in the Enumerable class, the syntax to call those methods should look as shown below using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; IEnumerable<int> EvenNumbers = Enumerable.Where(intList, n => n % 2 == 0); foreach(var i in EvenNumbers ) Console.WriteLine(i); Console.ReadKey(); } } }
  • 68.
    LINQ in C# LINQExtension Method in C#: LINQ (Language Integrated Query) extension methods in C# are a set of methods provided by the System.Linq namespace that extends the capabilities of collections (like arrays, lists, and other types implementing IEnumerable<T>) by adding query functionality. These methods enable querying collections using a SQL-like syntax directly in C#. Here’s an overview of some commonly used LINQ extension methods: Where: Filters a sequence based on a predicate. var filteredResult = collection.Where(item => item.Property == someValue);
  • 69.
  • 70.
  • 71.
  • 72.
    LINQ in C# LINQOperators in C# What are LINQ Operators? The LINQ Operators are nothing but a set of extension methods used to write the LINQ Query. These LINQ extension methods provide many useful features we can apply to the data source. Some of the features are filtering the data, sorting the data, grouping the data, etc. What are the Categories of LINQ Operators? LINQ (Language-Integrated Query) operators in C# provide a way to query and manipulate data from arrays, enumerable classes, XML, relational databases, and third-party data sources. The operators are divided into different categories based on their functionality:
  • 73.
    LINQ in C# ProjectionOperators: These operators transform the elements of a sequence into a new form. Common projection operators include Select and SelectMany.  Select: Projects each element of a sequence into a new form.  SelectMany: Projects each sequence element to an IEnumerable<T> and flattens the resulting sequences into one sequence. Filtering Operators: These are used for filtering data. The most common restriction operator is Where which applies a predicate to each element of a sequence and returns those that satisfy the condition.  Where: Filters a sequence of values based on a predicate.  OfType: Filters the elements of an array based on a specified type.
  • 74.
    LINQ in C# PartitioningOperators: These operators divide a sequence into two parts and return one of them. Examples include Take, Skip, TakeWhile, and SkipWhile.  Take: Returns a specified number of contiguous elements from the start of a sequence.  Skip: Bypasses a specified number of elements in a sequence and then returns the remaining elements.  TakeWhile: Returns elements from a sequence as long as a specified condition is true.  SkipWhile: Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
  • 75.
    LINQ in C# OrderingOperators: These operators arrange the elements of a sequence. Common ordering operators are OrderBy, OrderByDescending, ThenBy, and ThenByDescending.  OrderBy: Sorts the elements of a sequence in ascending order according to a key.  OrderByDescending: Sorts the elements of a sequence in descending order according to a key.  ThenBy: Performs a subsequent ordering of the elements in a sequence in ascending order.  ThenByDescending: Performs a subsequent ordering of the elements in a sequence in descending order.  Reverse: Inverts the order of the elements in a sequence.
  • 76.
    LINQ in C# GroupingOperators: These operators group elements of a sequence based on a specified key value. The most notable grouping operator is GroupBy.  GroupBy: Groups the elements of a sequence according to a specified key selector function. Join Operators: These operators are used to combine elements from two or more sequences. Common join operators are Join and GroupJoin.  Join: Joins two sequences based on matching keys.  GroupJoin: Groups elements from a sequence based on a key and joins them with elements from another sequence.
  • 77.
    LINQ in C# SetOperators: These operators perform mathematical set operations on sequences, such as Distinct, Union, Intersect, and Except.  Distinct: Removes duplicate elements from a sequence.  Union: Produces the set union of two sequences.  Intersect: Produces the set intersection of two sequences.  Except: Produces the set difference of two sequences.
  • 78.
    LINQ in C# ConversionOperators: These are used to convert one type of sequence or collection to another. Examples include ToArray, ToList, ToDictionary, and AsEnumerable.  AsEnumerable: Casts an IEnumerable to an IEnumerable<T>.  ToArray: Converts a sequence to an array.  ToList: Converts a sequence to a List<T>.  ToDictionary: Converts a sequence to a Dictionary<TKey, TValue> based on a key selector function.
  • 79.
    LINQ in C# ElementOperators: These operators return a single element from a sequence. Examples include First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault, and ElementAt.  First: Returns the first element of a sequence.  FirstOrDefault: Returns the first element of a sequence or a default value if no element is found.  Last: Returns the last element of a sequence.  LastOrDefault: Returns the last element of a sequence or a default value if no element is found.  Single: Returns the only element of a sequence and throws an exception if there is not exactly one element in the sequence.  SingleOrDefault: Returns the only element of a sequence or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.  ElementAt: Returns the element at a specified index in a sequence.  ElementAtOrDefault: Returns the element at a specified index in a sequence or a default value if the index is out of range.
  • 80.
    LINQ in C# QuantifierOperators: These operators return a Boolean value indicating whether all or any of the elements of a sequence satisfy a condition. Examples are All, Any, and Contains.  Any: Determines whether any element of a sequence satisfies a condition.  All: Determines whether all elements of a sequence satisfy a condition.  Contains: Determines whether a sequence contains a specified element. Equality Operators: These operators are used to compare sequences for equality. An example is SequenceEqual.  SequenceEqual: Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.
  • 81.
    LINQ in C# AggregateOperators: These operators perform a calculation on a sequence and return a single value. Examples include Count, Sum, Min, Max, Average, and Aggregate.  Count: Counts the elements in a sequence.  LongCount: Counts the elements in a sequence, returning the count as a long.  Sum: Computes the sum of a sequence of numeric values.  Min: Returns the minimum value in a sequence.  Max: Returns the maximum value in a sequence.  Average: Computes the average of a sequence of numeric values.  Aggregate: Applies an accumulator function over a sequence.
  • 82.
    LINQ in C# GenerationOperators: These operators are used to create a new sequence of values. Examples include Range, Repeat, and Empty.  Empty: Returns an empty IEnumerable<T> with the specified type argument.  Repeat: Generates a sequence that contains one repeated value.  Range: Generates a sequence of integral numbers within a specified range. Special Operators:  Concatenation Operators: These operators concatenate two sequences. The primary operator in this category is Concat.  DefaultIfEmpty Operators: This operator returns the elements of the specified sequence or the type parameter’s default value in a singleton collection if the sequence is empty.
  • 83.
    LINQ in C# LINQSelect Operator/Method in C# with Examples Projection Operators: These operators transform the elements of a sequence into a new form. Common projection operators include  Select  SelectMany. LINQ Select Operator/Method using C#: Create a console application named LINQDemo (you can give any meaningful name). Then, add a new class file with the name Employee.cs. Once you add the Employee.cs class file, copy and paste the following code.
  • 84.
  • 85.
    LINQ in C# Selectall the Employee data from the data source using both the LINQ Method and Query Syntax. Please look at the following image, which shows Query and Method Syntax to fetch all the Employees. The following image is self-explained. You need to remember that it is not executed when we form the query. When we call the ToList() Method, Sum() Method, etc., or use the Query variable within a for-each loop, only the Query will be executed.
  • 86.
  • 87.
  • 88.
    LINQ in C# usingSystem; using System.Collections.Generic; using System.Linq; public class HelloWorld { public static void Main(string[] args) { //Using Query Syntax List<Employee> basicQuery = (from emp in Employee.GetEmployees() select emp).ToList(); foreach (Employee emp in basicQuery) { Console.WriteLine($"ID : {emp.ID} Name : {emp.FirstName} {emp.LastName}"); } //Using Method Syntax IEnumerable<Employee> basicMethod = Employee.GetEmployees().ToList(); foreach (Employee emp in basicMethod) { Console.WriteLine($"ID : {emp.ID} Name : {emp.FirstName} {emp.LastName}"); } Console.ReadKey(); } }
  • 89.
    LINQ in C# publicclass Employee { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int Salary { get; set; } public static List<Employee> GetEmployees() { List<Employee> employees = new List<Employee> { new Employee {ID = 101, FirstName = "Preety", LastName = "Tiwary", Salary = 60000 }, new Employee {ID = 102, FirstName = "Priyanka", LastName = "Dewangan", Salary = 70000 }, new Employee {ID = 103, FirstName = "Hina", LastName = "Sharma", Salary = 80000 }, new Employee {ID = 104, FirstName = "Anurag", LastName = "Mohanty", Salary = 90000 }, new Employee {ID = 105, FirstName = "Sambit", LastName = "Satapathy", Salary = 100000 }, new Employee {ID = 106, FirstName = "Sushanta", LastName = "Jena", Salary = 160000 } }; return employees; } }
  • 90.
  • 91.
    LINQ in C# Howdo you Select a Single Property using LINQ Select Operator or Method in C#? Note: In the Query Syntax, the data type of the basicPropQuery variable is List<int>. This is because of the ToList() method applied to the Query Syntax. And because of this ToList() method, the query is executed at that point only. But in the case of Method Syntax, we have not applied the ToList() method, which is why the data type of the basicPropMethod variable is of IEnumerable<int> type. And more importantly, at that point, the query is generated but not executed. When we use the basicPropMethod variable within the for-each loop, the query will be executed at that time.
  • 92.
  • 93.
    LINQ in C# HowDoes It Work Internally?  Iteration: The Select operator iterates over each element in the source sequence.  Transformation: For each element, it applies the transformation logic defined in the lambda expression.  Result: It produces a new sequence where each element is the result of the applied transformation on the corresponding element from the source sequence.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.