LINQ Select Operator

LINQ Select Operator in C# with Examples

In this article, I am going to discuss the Projection Operators i.e. LINQ Select Operator 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

  1. What is Projection?
  2. What are Projection Operators and Methods in LINQ?
  3. How to use the Select Method?
  4. Basic Selection of Data
  5. How to Select Data to other class and to anonymous type?
  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 Query and Method syntax.

What is Projection?

Projection is nothing but the mechanism which is used to select the data from a data source. You can select the data in the same form (i.e. the original data in its original state). It is also possible to create a new form of data by performing some operations on it.

What are Projection Methods or Operators available in LINQ?

There are two methods available in projection. They are as follows

  1. Select
  2. SelectMany

In this article, we will discuss the Select Method and in the next article, we will discuss the SelectMany Method.

Select Operator:

As we know the Select clause in SQL allows us to specify what columns we want to retrieve, whether you want to retrieve all the columns or some of the columns that you need to specify the select clause.

In the same way, the LINQ Select operator also allows us to specify what properties we want to retrieve, whether you want to retrieve all the properties or some of the properties that you need to specify in the select operator. The standard LINQ Select Operator also allows us to perform some calculations.

Example:

Let us understand the select projection operator with some examples.

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 in 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 following four properties such as ID, FirstName, LastName, and Salary. We also created one static method which will return the list of employees which will act as our data source.

Let us discuss some examples to understand the LINQ Select Operator.

Example1:

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

LINQ Select Operator Query and Method Syntax

The complete code is given below.

Modify the Program class as shown below.

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 Select Operator?

Select all the Employees IDs only using both method and query syntax.

basic Select Query and Method Syntax to select a single property

Note:

In the Query Syntax, the data type of the basicPropQuery is List<int>, this is because of the ToList() method that we applied on 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 within the foreach loop, then at that time the query is executed.

The complete example is given below.

namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Query Syntax
            List<int> basicPropQuery = (from emp in Employee.GetEmployees()
                                        select emp.ID)
                                        .ToList();

            foreach (var id in basicPropQuery)
            {
                Console.WriteLine($"ID : {id}");
            }

            //Using Method Syntax
            IEnumerable<int> basicPropMethod = Employee.GetEmployees()
                                               .Select(emp => emp.ID);
            
            foreach (var id in basicPropMethod)
            {
                Console.WriteLine($"ID : {id}");
            }
            
            Console.ReadKey();
        }
    }
}
Example3:

Our requirement is to select only the Employee First Name, Last Name, and Salary properties. We don’t require to select the ID property.

Select Complex object using LINQ Projection Operator

The Complete 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 Data to another class using LINQ Projection Operator?

It is also possible to select the data to another class using the LINQ Select operator. In our previous example, we have selected the First Name, Last Name, and Salary properties to the same Employee class.

Let us create a new class with the above three properties. So, add a new class file with the name EmployeeBasicInfo.cs and then 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; }
    }
}

Now what we need to do here is, we need to the project the First Name, Last Name and Salary properties to the above newly created EmployeeBasicInfo class.

Selecting Data to Other Type using LINQ Select Operator

The complete example 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 Select Data to Anonymous Type using LINQ Select Operator?

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.

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

The complete 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 data selected using the LINQ Select Operator?

Let me first explain what we want to achieve. We want to perform the following calculations 

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

Then we need to select the ID, AnnualSalary, and FullName to an anonymous type.

Operations with LINQ Select Query

The Complete example 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?

It is also possible to select values using an integral index. The index is 0 based.

Using Index in LINQ Query

The Complete 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
                         {
                             IndexPosition = emp.index,
                             FullName = emp.value.FirstName + " " + emp.value.LastName,
                             Salary = emp.value.Salary
                         }).ToList();
            foreach (var emp in query)
            {
                Console.WriteLine($" Position {emp.IndexPosition} Name : {emp.FullName} Salary : {emp.Salary} ");
            }

            //Method Syntax
            var selectMethod = Employee.GetEmployees().
                                          Select((emp, index) => new
                                          {
                                              IndexPosition = index,
                                              FullName = emp.FirstName + " " + emp.LastName,
                                              Salary = 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 some examples. I hope this article gives you a very good understanding of the LINQ Select Operator.

Leave a Reply

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