LINQ Operators in C#
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.
Projection Operators:
These operators transform the elements of a sequence into a new form. Common
projection operators include Select and SelectMany.
1
These operators are used to combine elements from two or more sequences.
Common join operators are Join and GroupJoin.
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.
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; }
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();
3
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
4
}
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 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
});
//Method Syntax
List<Employee> selectMethod = Employee.GetEmployees().
Select(emp => new Employee()
{
FirstName = emp.FirstName,
LastName = emp.LastName,
Salary = emp.Salary
}).ToList();
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
});
//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?
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
});
//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
});
//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
});
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:
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