Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
47 views

LINQ - DotNetTutorials Notes

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

LINQ - DotNetTutorials Notes

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

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. It was
introduced with .NET Framework 3.5 & Visual Studio 2008.

Key Features of LINQ:

LINQ provides the following Key Features:

 Uniform Query Syntax: Whether you are querying an SQL database, an XML
document, or an in-memory collection, the syntax is consistent and typically
involves query operators like where, select, groupby, etc.
 Consistency: LINQ provides a consistent and uniform way to query different
data sources, simplifying code and reducing the need to learn multiple query
languages for different data types.
 Improved Productivity: LINQ simplifies common data operations like filtering,
sorting, and grouping, reducing the amount of repetitive code that developers
need to write.
 Strongly Typed: LINQ is strongly typed, which means the compiler checks
the syntax against the types of objects being queried, thus minimizing runtime
errors.
 SQL-Like Syntax: LINQ queries use a SQL-like syntax that is familiar to many
developers, making it easier to express complex data retrieval and
manipulation operations.
LINQ Supported Data Sources:

LINQ can be used with several data sources, and there are different flavors of LINQ
based on what you are querying:

 LINQ to Objects: Refers to using LINQ queries with any IEnumerable or


IEnumerable<T> collection directly in memory.
 LINQ to SQL: Allows querying of SQL Server databases, translating LINQ
queries into SQL queries that are then executed against the database.
 LINQ to XML (formerly known as XLINQ): Provides an in-memory XML
programming interface that leverages LINQ to offer a simpler and more
declarative way to read, manipulate, and write XML data.
 LINQ to Entities: A part of the ADO.NET Entity Framework, LINQ to Entities
allows querying data sources defined by the Entity Data Model (EDM) through
LINQ.
 LINQ to DataSet: Designed to work with ADO.NET DataSets, allowing for
queries on data cached in DataSet objects.
For whom?

These LINQ tutorials using C# are designed for beginners and professional
developers who want to learn LINQ in C# step by step, from the very basic to the
advanced concept, using real-time examples. These tutorials provide a hands-on
approach to the subject with step-by-step program examples that will assist you in
learning and putting the acquired knowledge into practice.

What will you learn from these LINQ Tutorials?


This LINQ Tutorial using C# will start with the basics of LINQ, and as we progress,
we will also cover the advanced topics. Here, we explain each topic with easy-to-
understand explanations, real-time examples, and important notes to remember.
These LINQ tutorials are divided into a series of related topics so that it will be good
for you to start from a topic that must be understood first, and then gradually, you will
learn other concepts of LINQ.

Prerequisites to Learn LINQ:

To learn LINQ effectively, you should understand several foundational concepts and
technologies in the .NET framework and C# (or another .NET language that supports
LINQ, such as VB.NET). Here are the prerequisites that will help you grasp LINQ
more quickly and thoroughly:

 Basic Knowledge of C# or a Similar .NET Language: Since LINQ is a part


of .NET languages, you need to be comfortable with at least one of
them, C# being the most common. This includes understanding variables,
control flow (if, loops), methods, classes, and exception handling.
 Understanding of Object-Oriented Programming (OOP): Familiarity
with OOP Principles is essential since LINQ often operates on collections of
objects. You should understand concepts like classes, objects, inheritance,
polymorphism, and encapsulation.
 Collections in .NET: A good grasp of the Collection Framework in .NET,
such as Arrays, List<T>, Dictionary<TKey, TValue>, and especially the
interfaces IEnumerable and IEnumerable<T>, since these are the core
interfaces that LINQ queries work with.
 Generics: Understanding Generics in .NET is important because LINQ is
heavily based on generic collections (IEnumerable<T>, IQueryable<T>, etc.).
 Delegates and Events: Since LINQ is built on the concepts
of delegates, anonymous methods, and lambda expressions for creating inline
functions, knowledge of these concepts is very helpful.
 Lambda Expressions: LINQ heavily relies on Lambda Expressions to
express criteria, projections, and transformations within queries. They provide
a concise way to represent anonymous methods.
 Extension Methods: LINQ queries are implemented as Extension
Methods for the IEnumerable and IQueryable types. Understanding how
extension methods work will help you understand how LINQ integrates with
object collections.
 Anonymous Types: LINQ frequently uses Anonymous Types to store select
query results. Knowing how they work will allow you to easily create and
manipulate such types.
 Knowledge of SQL and Databases (for LINQ to SQL/Entities): If you plan
on using LINQ to interact with databases, a basic understanding of SQL and
relational database concepts will be necessary.
Note: If we missed any topics in this C# LINQ Tutorials, then please let us know by
giving a comment in the Comment Box, and we promise as soon as possible, we will
publish articles on that topic.

Architecture of LINQ
In this article, I am going to discuss the Architecture of LINQ. The term LINQ stands
for Language Integrated Query, and it is pronounced as LINK. Nowadays, the use
of use LINQ is increasing rapidly. So, as a developer, you should understand LINQ
and its architecture. At the end of this article, you will have a very good
understanding of the following pointers.

1. What is LINQ?
2. Why should we learn LINQ?
3. How does LINQ work?
4. What are LINQ Providers?
5. When to Use LINQ?
6. Advantages and Disadvantages of using 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.

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.
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.

How Does LINQ Work?

Please look at the following diagram to understand how the LINQ works in the .NET
Framework.

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.
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.

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.
 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.

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;
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);
When to Use LINQ?

Knowing when to use LINQ is important for writing clean, efficient, and maintainable
code. Here are some scenarios where LINQ is particularly useful:

 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.
 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.
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.
What are the Disadvantages of using LINQ?

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.
In the next article, I will discuss the Different Ways to Write LINQ Queries using
C#.NET. I try to explain the Architecture of LINQ in this article, and I hope you enjoy
this LINQ Architecture article.

Different Ways to Write LINQ Queries in C# with


Examples
In this article, I will discuss the Different Ways to write LINQ Queries, i.e., LINQ
Query Syntax and Method Syntax with Examples using C#. Please read our previous
article discussing the Architecture of LINQ, i.e., how LINQ works.

What are the different things required to write a LINQ Query?

To write a LINQ query, we need the following three things

1. Data Source (In-Memory Objects, SQL Server, XML Document, etc)


2. Query
3. Execution of the Query
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)
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.

1. Query Syntax
2. Method Syntax
3. 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.
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.

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. 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.
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.
Let us understand how to use Query Syntax, Method Syntax, and Mixed Syntax with
examples. We have an integer list, and we need to write a LINQ query to return all
the integers greater than 5. We are going to create a console application.

Example Using LINQ Query Syntax in C#:

The following Example code is self-explained, so please go through the comment


lines. Here, we have created a collection of integers, i.e., going to be our data
source. Then, we created one LINQ query, which will fetch the numbers from the
data source that are greater than 5, and finally, we executed the query and printed
the result on the Console window. The LINQ query contains three things, i.e., Data
Source, Condition, and Selection.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
//Step1: Data Source
List<int> integerList = new List<int>()
{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
//Step2: Query
//LINQ Query using Query Syntax to fetch all
numbers which are > 5
var QuerySyntax = from obj in integerList
//Data Source
where obj > 5 //Condition
select obj; //Selection
//Step3: Execution
foreach (var item in QuerySyntax)
{
Console.Write(item + " ");
}
Console.ReadKey();
}
}
}
Now run the application, and it will display the values 6 7 8 9 10 as expected in the
console window. Let us understand what we did in the above code.

Example Using LINQ Method Syntax in C#:


Let us rewrite the previous example using the LINQ Method Syntax. The following
Example code is self-explained, so please go through the comment lines.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
//Step1: Data Source
List<int> integerList = new List<int>()
{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
//Step2: Query
//LINQ Query using Query Syntax to fetch all
numbers which are > 5
var QuerySyntax = integerList.Where(obj => obj
> 5).ToList();
//Step3: Execution
foreach (var item in QuerySyntax)
{
Console.Write(item + " ");
}
Console.ReadKey();
}
}
}
Now, run the application, and you will get the output as expected. Let us have a look
at the following diagram to understand Method Syntax.
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.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
//Data Source
List<int> integerList = new List<int>()
{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
//LINQ Query using Mixed Syntax
var MethodSyntax = (from obj in integerList
where obj > 5
select obj).Sum();
//Execution
Console.Write("Sum Is : " + MethodSyntax);
Console.ReadKey();
}
}
}
Now, run the application, and you will see the output as expected. Let us understand
what we did in the above code by looking at the following image.

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.

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).
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).
In the next article, I will discuss IEnumerable and IQuerable in LINQ with
Examples. I hope you enjoy this article and understand the Linq Query Syntax and
Linq Method Syntax with Examples.

IEnumerable and IQueryable in C# with


Examples
In this article, I will discuss IEnumerable and IQueryable in C# with Examples.
Please read our previous article discussing How to write LINQ Queries with
Examples. In C#, IEnumerable and IQueryable are two interfaces that are frequently
used for data manipulation and querying, but they serve different purposes and have
distinct behaviors.

Example to Understand IEnumerable and IQueryable in C#

Let us understand these two interfaces with examples. Please look at the following
program we wrote using the LINQ Query Syntax in our previous article.

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.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
List<int> integerList = new List<int>()
{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
IEnumerable<int> QuerySyntax = from obj in
integerList
where obj > 5
select obj;
foreach (var item in QuerySyntax)
{
Console.Write(item + " ");
}
Console.ReadKey();
}
}
}
With this kept in mind, let us understand what IEnumerable is.

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.
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.

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.
Example to understand IEnumerable with Complex Type using
C#:

Whenever we want to work with in-memory objects, we need to use the IEnumerabe
interface, and the reason for this will be discussed in our next article. In the below
example, we have a complex type called Student. Within the Main method, we
created a collection to hold a list of students. Then, we are required to display only
the Male students. For this, we are using the LINQ Query to fetch the Male students
from the student collection data source, and then using a for each loop, we are
iterating through the IEnumerable<Student> collection.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
List<Student> studentList = new List<Student>()
{
new Student(){ID = 1, Name = "James", Gender =
"Male"},
new Student(){ID = 2, Name = "Sara", Gender =
"Female"},
new Student(){ID = 3, Name = "Steve", Gender =
"Male"},
new Student(){ID = 4, Name = "Pam", Gender =
"Female"}
};
//Linq Query to Fetch all students with Gender
Male
IEnumerable<Student> QuerySyntax = from std in
studentList
where std.Gender == "Male"
select std;
//Iterate through the collection
foreach (var student in QuerySyntax)
{
Console.WriteLine( $"ID : {student.ID} Name :
{student.Name}");
}
Console.ReadKey();
}
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
}
}
When we execute the program, the result will be displayed as expected, as shown in
the image below.

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.

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.
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.
Example to Understand IQueryable<T> Interface in C#.

The following is the same example as the previous one. Instead of


IEnumerable<Student>, we store the result in the IQuerable<Student> variable. To
store the result in the IQuerable<Student> variable, we need to call the
AsQueryable() method on the data source.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
List<Student> studentList = new List<Student>()
{
new Student(){ID = 1, Name = "James", Gender =
"Male"},
new Student(){ID = 2, Name = "Sara", Gender =
"Female"},
new Student(){ID = 3, Name = "Steve", Gender =
"Male"},
new Student(){ID = 4, Name = "Pam", Gender =
"Female"}
};
//Linq Query to Fetch all students with Gender
Male
IQueryable<Student> MethodSyntax =
studentList.AsQueryable()
.Where(std => std.Gender == "Male");
//Iterate through the collection
foreach (var student in MethodSyntax)
{
Console.WriteLine( $"ID : {student.ID} Name :
{student.Name}");
}
Console.ReadKey();
}
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
}
}
Now run the application, and you will see the data as expected, as shown in the
below image.

The point you need to remember is to return a collection of IQueryable type and call
the AsQueryable() method on the data source, as we did in the above example.

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.
In the next article, I will discuss the Differences Between IEnumerable and
IQueryable in C# and when to use one over another with an example. I hope this
article gives you a good understanding of two important interfaces, i.e., IEnumerable
and IQueryable in C# with Examples.

Differences Between IEnumerable and


IQueryable in C#
In this article, I will discuss the Differences Between IEnumerable and IQueryable
in C# with Examples. Please read our previous article before proceeding to this
article, where we discussed the basics of IEnumerable and IQueryable in C# with
Examples.

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.

Advertisements

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.
Please use the SQL script below to create and populate the Student table with the
required test data.

-- Create the required Student table


CREATE TABLE Student
(
ID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Gender VARCHAR(50)
)
GO
-- Insert the required test data
INSERT INTO Student VALUES (101, 'Steve',
'Smith', 'Male')
INSERT INTO Student VALUES (102, 'Sara',
'Pound', 'Female')
INSERT INTO Student VALUES (103, 'Ben',
'Stokes', 'Male')
INSERT INTO Student VALUES (104, 'Jos',
'Butler', 'Male')
INSERT INTO Student VALUES (105, 'Pam', 'Semi',
'Female')
GO
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.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
using (StudentDBContext DBContext = new
StudentDBContext())
{
//To See What SQL Generated By Entity Framework
DBContext.Database.Log = Console.Write;
//Fetch the Top 2 Records from the Students
Database table where Gender = Male
IEnumerable<Student> listStudents =
DBContext.Students.Where(x => x.Gender ==
"Male");
listStudents = listStudents.Take(2);
Console.WriteLine("Top 2 Student Where Gender =
Male");
foreach (var std in listStudents)
{
Console.WriteLine(std.FirstName + " " +
std.LastName);
}
}
Console.ReadKey();
}
}
}
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.

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.

using System;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
using (StudentDBContext DBContext = new
StudentDBContext())
{
//To See What SQL Generated By Entity Framework
DBContext.Database.Log = Console.Write;
//Fetch the Top 2 Records from the Students
Database table where Gender = Male
IQueryable<Student> listStudents =
DBContext.Students
.AsQueryable()
.Where(x => x.Gender == "Male");
listStudents = listStudents.Take(2);
Console.WriteLine("Top 2 Student Where Gender =
Male");
foreach (var std in listStudents)
{
Console.WriteLine(std.FirstName + " " +
std.LastName);
}
}
Console.ReadKey();
}
}
}
Here, we create the LINQ Query using IQueryable. With the above changes in
place, now run the application and see the output. You should get the
following output.

AD
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#.

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#. Here’s a comparison:

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.
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).
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.
Query Translation:

 IEnumerable: LINQ methods are executed in memory on the entire data set.
Filtering, sorting, and other operations are performed locally.
 IQueryable: LINQ methods are translated into a query language specific to the
data source (e.g., SQL) and executed on the data source. This allows for
efficient server-side operations.
Suitable Use Cases:

 IEnumerable: Suitable for working with small to moderate-sized in-memory


collections where the entire data set can fit in memory. Typically used for in-
memory data manipulation and querying.
 IQueryable: Suitable for working with large data sets or data sources external
to the application, such as databases. It is ideal for offloading query execution
to the data source, enabling efficient database querying.
Common Use Cases:

 IEnumerable: Used for querying and manipulating in-memory collections,


filtering data, and applying transformations.
 IQueryable: Used with Entity Framework for querying databases using LINQ,
where queries are translated into SQL statements.
Examples:

 IEnumerable: Querying and filtering a list of objects in memory. Working with


arrays or lists.
 IQueryable: Querying a database using Entity Framework. Querying data
from a web service or remote data source.
Performance:
 IEnumerable: When querying data sources like databases, IEnumerable can
be less efficient because it retrieves all the data from the database and then
filters records in the client’s memory.
 IQueryable: IQueryable can be more efficient for large datasets and database
operations since it sends query expressions to the database, which then
returns the filtered result.
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.
In the next article, I will discuss the LINQ Extension Methods in C# with Examples.
In this article, I explain the Differences Between IEnumerable and IQueryable in
C#. I hope this article gives you a very good understanding of the Differences
Between IEnumerable and IQueryable in C# with Examples.

LINQ Extension Methods in C# with Examples


In this article, I will discuss the LINQ Extension Methods in C# with Examples.
Please read our previous article before proceeding to this article, where we
discussed the Differences between IEnumerable and IQueryable in C#. At the end
of this article, you will understand the following three concepts in C#.

1. What are Extension Methods in C#?


2. When should you use Extension Methods in C#?
3. How do you implement extension methods in C#?
4. Understanding the LINQ Extension Methods.
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.

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#.

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.

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.

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.

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);

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.

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;
}
}
}
Now run the application, and you will see the word count as expected in the console
window. Here, we can still call the GetWordCount() extension method using the
wrapper class style syntax and get the output as expected, as shown below.

So, the point that I need to keep focus on is that this is how the extension methods
are called internally behind the scenes.

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);
Console.ReadKey();
}
}
}
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);

Select: Projects each element of a sequence into a new form.


var projectedResult = collection.Select(item => new { item.Property1,
item.Property2 });

OrderBy / OrderByDescending: Sorts the elements of a sequence in ascending or


descending order.
var sortedResult = collection.OrderBy(item => item.Property);
var sortedDescendingResult = collection.OrderByDescending(item =>
item.Property);

GroupBy: Groups the elements of a sequence.


var groupedResult = collection.GroupBy(item => item.Property);

FirstOrDefault / LastOrDefault: Returns the first or last element of a sequence or a


default value if no element is found.
var firstItem = collection.FirstOrDefault();
var lastItem = collection.LastOrDefault();
Sum / Min / Max / Average: Computes the sum, minimum, maximum, or average of
a sequence.
var total = collection.Sum(item => item.NumericProperty);

Any / All: Checks if any or all sequence elements satisfy a condition.


bool hasItems = collection.Any();
bool allMatchCondition = collection.All(item => item.Property > someValue);

Distinct: Returns distinct elements from a sequence.


var distinctItems = collection.Distinct();

Count: Counts the elements in a sequence, optionally matching a specific condition.


int count = collection.Count();
int conditionalCount = collection.Count(item => item.Property == someValue);

Intersect / Except / Union: Performs set operations like intersection, difference, and
union on sequences.
var commonElements = collection1.Intersect(collection2);

In the next article, I will discuss the LINQ Operators in C# with Examples. In this
article, I try to explain the Linq Extension Methods in C# with Examples. I hope you
enjoy this LINQ Extension Methods in C# article.

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:

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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
These operators provide powerful capabilities for querying and manipulating
collections in C#. They can be used with various types of data sources, including
arrays, lists, XML, and even databases through LINQ to SQL or Entity Framework. In
the next article, I will discuss Projection Operations with examples.

following pointers related to LINQ Select Projection Operator in C#.

1. What is Projection?
2. What are Projection Operators and Methods Available in LINQ?
3. How do you use the LINQ Select Method or Select Operator?
4. Examples to Understand Basic Projection of Data to the Same Type.
5. How do you project data to different Classes and Anonymous Types?
6. Performing Calculations on the Selected data using LINQ Select
Operator.
7. How to Select Data with Index Value?
8. When should you use the LINQ Select Method in C#?
Note: We will discuss each example using LINQ Query and Method Syntax. Again,
when I am saying LINQ Operator or Method, the meaning is going to be same.

What is Projection in LINQ?

Projection in LINQ is nothing but a mechanism used to select the data from a data
source. You can select the data in the same form (i.e., the original form). It is also
possible to create a new form of data by performing some operations on it. So, in
simple words, we can say that Projection is an operation that converts an object into
a new form that holds only those properties as per our requirements.
What are Projection Methods or Operators Available in LINQ?

There are two methods available in the projection operator category in LINQ. They
are as follows.

1. Select
2. SelectMany
In this article, we will discuss the LINQ Select Method with Examples, and in the
next article, we will discuss the LINQ SelectMany Method with Examples.

LINQ Select Operator/Method using C#:

The LINQ Select Projection Operator or Method can be used to format the query’s
result as per our requirement. The LINQ Select Operator can return a scaler value, a
custom class, a collection of custom classes, or an anonymous type, which includes
properties per our business requirements.

The Select Clause in SQL allows us to specify what columns we want to retrieve.
Whether we want to retrieve all the columns or some of the columns that we need to
specify in the select clause of the SQL Statement. In the same way, the LINQ Select
operator allows us to specify what properties we want to retrieve. We need to specify
whether we want to retrieve all or some of the properties in the Select Operator. The
LINQ Select Method also allows us to perform some calculations.

Examples to Understand LINQ Select Operator using C#:

Let us understand the LINQ Select Projection Operator with Examples using C#
Language. Here, we are going to use a Console Application. So first, 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.

using System.Collections.Generic;
namespace LINQDemo
{
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;
}
}
}
As you can see, we created the Employee class with the four properties: ID,
FirstName, LastName, and Salary. We also created one static method to return the
hard-coded list of employees, which will act as our data source. Let us discuss some
examples to understand the LINQ Select Operator. The point that you need to
remember is that while using the Query Syntax, I will use the term Select as
Operator, and while using the Method Syntax, I will use the term Select as Method.

Example to Understand LINQ Select Projection Operator/Method


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.
Modify the Main Method of the Program class as follows. In the below code, we are
using the Select Method and Select Operator to return the data in its original shape.
That means the return data shape will be identical to the Student class shape (i.e.,
the same properties).

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
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();
}
}
}
How do you Select a Single Property using LINQ Select Operator
or Method in C#?

In our previous example, we returned the data in its original form, i.e., returning all
the properties of the Student class. We don’t want to return all the properties; we
want to return a single property value. Our requirement is to Select all the Employee
IDs using the LINQ Method and Query syntax. In that case, we need to specify the ID
property within the Select Operator or Method as follows:

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.

The Complete Example Code is Given Below.


using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
//Using Query Syntax
List<int> basicPropQuery = (from emp in
Employee.GetEmployees()
select emp.ID)
.ToList(); //At this Point the Query is
Executed
foreach (var id in basicPropQuery)
{
Console.WriteLine($"ID : {id}");
}
//Using Method Syntax
IEnumerable<int> basicPropMethod =
Employee.GetEmployees()
.Select(emp => emp.ID);
//At this Point the Query is Just Generated,
Not Executed
foreach (var id in basicPropMethod) //At this
Point the Query is going to be Executed
{
Console.WriteLine($"ID : {id}");
}
Console.ReadKey();
}
}
}
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.
Deferred Execution: An important aspect of the Select operator in LINQ is that it
uses deferred execution. This means that the actual transformation of elements
doesn’t happen when you define the Select call but when you iterate over the
resulting sequence. This can be important for performance, especially with large data
sets or complex queries.

How do you Select a Few Properties using LINQ Select Operator


or Select Method in C#?

We have discussed selecting all the properties and a single property using LINQ
Select Projection Operator and Method. Now, let us proceed and try to understand
how to select a few properties using LINQ Select Projection Operator and Method
with an example.

Our requirement is to select only the Employee’s First Name, Last Name, and Salary
properties. We don’t want to select the employee’s ID property. For a better
understanding, please have a look at the following image. In the code below, we
select the First Name, Last Name, and Salary properties of the same Employee
class. Later, I will show you how to project these properties to a different class and
an anonymous type. With the Select Operator or Method, we create an instance of
the Employee class and populate the First Name, Last Name, and Salary properties
from the data source which we can access using the emp object.

The Complete Example Code is Given Below.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
//Query Syntax
IEnumerable<Employee> selectQuery = (from emp
in Employee.GetEmployees()
select new Employee()
{
FirstName = emp.FirstName,
LastName = emp.LastName,
Salary = emp.Salary
});
foreach (var emp in selectQuery)
{
Console.WriteLine($" Name : {emp.FirstName}
{emp.LastName} Salary : {emp.Salary} ");
}
//Method Syntax
List<Employee> selectMethod =
Employee.GetEmployees().
Select(emp => new Employee()
{
FirstName = emp.FirstName,
LastName = emp.LastName,
Salary = emp.Salary
}).ToList();
foreach (var emp in selectMethod)
{
Console.WriteLine($" Name : {emp.FirstName}
{emp.LastName} Salary : {emp.Salary} ");
}
Console.ReadKey();
}
}
}
How do you Select a Few Properties to a Different class using a
LINQ Select Operator?

It is also possible to project or select the data to a different class using the LINQ
Select Operator or Method. In our previous example, we have seen how to select a
few properties (First Name, Last Name, and Salary properties) to the same class
using the LINQ Select Projection Operator. Let us create a new class with the above
three properties, and we will project the data to this class. So, please create a new
class file named EmployeeBasicInfo.cs and copy and paste the following code.

namespace LINQDemo
{
public class EmployeeBasicInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Salary { get; set; }
}
}
We need to select the First Name, Last Name, and Salary properties to the above
newly created EmployeeBasicInfo class. For a better understanding, please have a
look at the below image. Now, with the Select Method or Operator, we are not
creating an instance of the Employee class. We are creating an instance of the
EmployeeBasicInfo class and populating the FirstName, LastName, and Salary
properties from the data source we can access using the emp object.

Advertisements
AD

The Complete Example Code is Given Below.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
//Query Syntax
IEnumerable<EmployeeBasicInfo> selectQuery =
(from emp in Employee.GetEmployees()
select new EmployeeBasicInfo()
{
FirstName = emp.FirstName,
LastName = emp.LastName,
Salary = emp.Salary
});
foreach (var emp in selectQuery)
{
Console.WriteLine($" Name : {emp.FirstName}
{emp.LastName} Salary : {emp.Salary} ");
}
//Method Syntax
List<EmployeeBasicInfo> selectMethod =
Employee.GetEmployees().
Select(emp => new EmployeeBasicInfo()
{
FirstName = emp.FirstName,
LastName = emp.LastName,
Salary = emp.Salary
}).ToList();
foreach (var emp in selectMethod)
{
Console.WriteLine($" Name : {emp.FirstName}
{emp.LastName} Salary : {emp.Salary} ");
}
Console.ReadKey();
}
}
}
How do you project the data to Anonymous Type using LINQ
Select Operator/Method?

Instead of projecting the data to a particular type like Employee or


EmployeeBasicInfo, we can also project the data to an anonymous type in LINQ
using the Select Method or Operator. For a better understanding, please have a look
at the below image. Here, we are creating an anonymous object (i.e., creating an
object without specifying the type) and creating and populating the FirstName,
LastName, and Salary properties from the data source which we can access using
the emp object.

The Complete Example Code is Given Below.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
//Query Syntax
var selectQuery = (from emp in
Employee.GetEmployees()
select new
{
FirstName = emp.FirstName,
LastName = emp.LastName,
Salary = emp.Salary
});
foreach (var emp in selectQuery)
{
Console.WriteLine($" Name : {emp.FirstName}
{emp.LastName} Salary : {emp.Salary} ");
}
//Method Syntax
var selectMethod = Employee.GetEmployees().
Select(emp => new
{
FirstName = emp.FirstName,
LastName = emp.LastName,
Salary = emp.Salary
}).ToList();
foreach (var emp in selectMethod)
{
Console.WriteLine($" Name : {emp.FirstName}
{emp.LastName} Salary : {emp.Salary} ");
}
Console.ReadKey();
}
}
}
How do you Perform Calculations on Selected Data using the
LINQ Select Operator?

Let me first explain what we want to achieve. We want to perform the following
calculations on the selected employee data. We need to calculate the Annual Salary
and merge the First and Last Name as Full Name in the output.

1. AnnualSalary = Salary*12
2. FullName = FirstName + ” ” + LastName
Once we do the above calculation, we need to project the ID, AnnualSalary, and
FullName to an anonymous type using the LINQ Projection Operator. For a better
understanding, please have a look at the following image.
The Complete Example Code is Given Below.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
//Query Syntax
var selectQuery = (from emp in
Employee.GetEmployees()
select new
{
EmployeeId = emp.ID,
FullName = emp.FirstName + " " + emp.LastName,
AnnualSalary = emp.Salary * 12
});
foreach (var emp in selectQuery)
{
Console.WriteLine($" ID {emp.EmployeeId} Name :
{emp.FullName} Annual Salary :
{emp.AnnualSalary} ");
}
//Method Syntax
var selectMethod = Employee.GetEmployees().
Select(emp => new
{
EmployeeId = emp.ID,
FullName = emp.FirstName + " " + emp.LastName,
AnnualSalary = emp.Salary * 12
}).ToList();
foreach (var emp in selectMethod)
{
Console.WriteLine($" ID {emp.EmployeeId} Name :
{emp.FullName} Annual Salary :
{emp.AnnualSalary} ");
}
Console.ReadKey();
}
}
}
How do you Select Data with Index Value using LINQ Select
Projection Operator?

It is also possible to select values using an integral index. The index is 0 based. The
index will be from 0 to 4 if the query fetches five records. It’s a unique value to each
record we select or project from the data source.

The Complete Example Code is Given Below.

using System;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
//Query Syntax
var query = (from emp in
Employee.GetEmployees().Select((value, index)
=> new { value, index })
select new
{
//Index is 0-Based, and always increases by 1
IndexPosition = emp.index,
FullName = emp.value.FirstName + " " +
emp.value.LastName,
emp.value.Salary
}).ToList();
foreach (var emp in query)
{
Console.WriteLine($" Position
{emp.IndexPosition} Name : {emp.FullName}
Salary : {emp.Salary} ");
}
//Method Syntax
//Projects each element of a sequence into a
new form by incorporating the element's index.
var selectMethod = Employee.GetEmployees().
Select((emp, index) => new
{
//Index is 0-Based, and always increases by 1
IndexPosition = index,
FullName = emp.FirstName + " " + emp.LastName,
emp.Salary
});
foreach (var emp in selectMethod)
{
Console.WriteLine($" Position
{emp.IndexPosition} Name : {emp.FullName}
Salary : {emp.Salary} ");
}
Console.ReadKey();
}
}
}
When should you use the LINQ Select Operator in C#?

The Select operator projects each sequence element into a new form. This is
analogous to the SELECT statement in SQL, which picks out specific columns of
data from a table. Here are several scenarios when you might use it:

 Transforming Data Types or Shapes: When you need to convert elements


of a collection from one type to another or when you need to transform them
into a new form. For instance, extracting specific properties from objects to
create a new collection of simpler objects or anonymous types.
 Data Projection: When you’re querying a data source, like a database or an
XML file, and you want to project the data into a different form. This is
particularly common in database operations where you only need specific
columns from a table.
 Applying Calculations or Methods: If you need to apply a calculation or
method to each element in a collection, Select can be used to produce a new
collection with the results. For example, calculating the square of each number
in a list.
 Fluent Method Chaining: LINQ Select is often used in conjunction with other
LINQ methods like Where, OrderBy, GroupBy, etc., in a fluent syntax to
perform complex queries and transformations in a readable and concise
manner.
 Performance Optimizations: In some cases, using Select can be more
efficient, especially when working with large collections or databases, as it
allows for the transformation of data as it is being retrieved or processed.
 Index-based Selection: The Select operator can also provide the index of
each element in the lambda expression, which can be used for more complex
transformations that might depend on the element’s position within the
collection.
 Creating Computed Values: When you want to compute and add new values
to each element in a collection based on some criteria or calculations. This
helps create derived values or aggregations.
 Querying and Filtering: When you want to filter or query data based on
certain conditions, create a new collection of matching elements. Allows you to
refine your data set based on specific criteria.
That’s it for today. In the next article, I will discuss the SelectMany Projection
Operator in C# with Examples. In this article, I try to explain the LINQ Select
Projection Operator/Method in C# with examples. I hope you enjoy this LINQ Select
Projection Operator/Method in C# with Examples article.

You might also like