0% found this document useful (0 votes)
13 views

LINQ Operators in C#

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)
13 views

LINQ Operators in C#

Uploaded by

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

LINQ Operators in C#

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:

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

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.

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

Select
SelectMany

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.

2
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#:

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

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)


{

3
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();
}
}
}

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.

The point that we 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.

Select all the Employee data from the data source using both the LINQ Method
and Query Syntax

You need to remember that it is not executed when we form the query. When we
call the ToList() Method, Sum() Method, etc., We use the Query variable within a
for-each loop, then only the Query will be executed.

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:

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

4
}

//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();
}
}
}

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.

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. In the code
below, we select the First Name, Last Name, and Salary properties of the same
Employee class. 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.

using System;
using System.Collections.Generic;

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

namespace LINQDemo
{
public class EmployeeBasicInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }

6
public int Salary { get; set; }
}
}
We need to select the First Name, Last Name, and Salary properties to the above
newly created EmployeeBasicInfo class.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.
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

7
using the Select Method or Operator.. 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.
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?
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.

AnnualSalary = Salary*12
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

using System;

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

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

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

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

11

You might also like