LINQ Select Projection Operator in C#

LINQ Select Projection Operator/Method in C# with Examples

In this article, I am going to discuss the LINQ Select Projection Operator/Method in C# with Examples. Please read our previous article where we discussed what are LINQ Operators and the different categories of LINQ Operators in C#. At the end of this article, you will understand the 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 to use the LINQ Select Method or Select Operator?
  4. Examples to Understand Basic Projection of Data to the Same Type,
  5. How to Project Data to Different Classes and to Anonymous Types?
  6. Performing Calculations on the Selected data using LINQ Select Operator.
  7. How to Select Data with Index Value?

Note: We will discuss each example using both LINQ Query and Method Syntax.

What is Projection in LINQ?

Projection in LINQ is nothing but a mechanism that is used to select the data from a data source. You can select the data in the same form (i.e. the data in its 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 and Select Method using C#:

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

As we know 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, we need to specify in the select clause of the SQL Statement.

In the same way, the LINQ Select operator or Select Method also allows us to specify what properties we want to retrieve. Whether we want to retrieve all the properties or some of the properties, we need to specify in the Select Operator or in the Select Method. The standard LINQ Select Operator or Select Method also allows us to perform some calculations. If this is not clear at the moment, then don’t worry, we will understand everything with examples.

Examples to Understand LINQ Select Method and Select Operator using C#:

Let us understand the LINQ Select Projection Operator or Select Method with Examples using C# Language. Here we are going to use a Console Application. So first create a console application with the name 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, then copy and paste the following code into it.

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 have created the Employee class with the four properties such as ID, FirstName, LastName, and Salary. We also created one static method which will 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 or Select Method. The point that you need to remember 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 LINQ Method and Query Syntax. Please have a look at the following image which shows both Query and Method Syntax to fetch all the Employees. The following image is self-explained. The point that you need to remember when we form the query, it is not executed. When we call the ToList() Method, Sum() Method, etc., or when we use the Query variable within a for-each loop, at that time only the Query is going to be executed.

LINQ Select Operator in C# using Query and Method Syntax

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 the same as the Student class shape (i.e. 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 to Select a Single Property using LINQ Select Operator or Select 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. Now, we don’t want to return all the properties rather we want to return a single property value. Our requirement is to Select all the Employee IDs using both LINQ Method and Query syntax. In that case, within the Select Operator or Select Method, we need to specify the ID property as shown in the below image.

basic Select Query and Method Syntax to select a single property

Note: In the Query Syntax, the data type of the basicPropQuery variable is List<int>, this is because of the ToList() method that we 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 and this is the reason why the data type of the basicPropMethod variable is of IEnumerable<int> type. And more importantly, at that point, the query is just generated but not executed. When we use the basicPropMethod variable within the for-each loop, then at that time the query is going to be executed.

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 to Select a Few Properties using LINQ Select Operator or Select Method in C#?

As of now, we have discussed how to select all the properties and how to select 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 require you to select the ID property of the Employee. For a better understanding, please have a look at the following image. The below image is self-explained. In the below code, we are selecting the First Name, Last Name, and Salary properties to the same Employee class. Later, I will show you how to project these properties to a different class and to an anonymous type. With the Select Operator or Select Method, we are creating an instance of the Employee class and populating the First Name, Last Name, and Salary properties from the data source which we can access using the emp object.

Select Complex object using LINQ Projection Operator

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 to Select a Few Properties to a Different Class using LINQ Projection Operator?

It is also possible to project or select the data to a different class using the LINQ Select Operator or Select 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 to this class, we will project the data. So, create a new class file with the name EmployeeBasicInfo.cs and then copy and paste the following code into it.

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

Now what we need to do here is, 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 select operator, we are not creating an instance of the Employee class, rather we are creating an instance of the EmployeeBasicInfo class and populating the FirstName, LastName, and Salary properties from the data source which we can access using the emp object.

Selecting Data to Other Type using LINQ Select Operator

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 to Project the Data to Anonymous Type using LINQ Select Operator/Method?

Instead of projecting the data source 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 select 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.

C:\Users\Pranaya\Pictures\Project to Anonymous Type using LINQ.PNG

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 to Perform Calculations on Select Data using the LINQ Projection Operator?

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

  1. AnnualSalary = Salary*12
  2. FullName = FirstName + ” ” + LastName

Once we do the above calculation, then 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.

Operations with LINQ Select Query

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 to 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. If the query fetches five records, then the index will be from 0 to 4. It’s basically a unique value to each record that we select or project from the data source.

Using Index in LINQ Query

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

That’s it for today. In the next article, I am going to discuss the SelectMany Projection Operator in C# with Examples. Here, 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.

4 thoughts on “LINQ Select Projection Operator in C#”

  1. Very good tutorials. But could you please add more details in the last example, particularly about second argument in this lambda expresion, how does it increment IndexPosition?
    And also how did you use Employee.GetEmployees().Select((value, index) in a querry syntax in the last example as well.

    1. SIDDHARTH RAWAT

      public static IEnumerable Select(this IEnumerable source, Func selector);

      This is the another extension method implemented for the same.

    2. The index variable, like value variable retrieves a property from the data namely the index position or where in the list that particular value is. Great tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *