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

LINQ Select Operator in C

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

LINQ Select Operator in C

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

LINQ Select Operator in C#

Back to: LINQ Tutorial For Beginners and Professionals


LINQ Select Projection Operator in C# with Examples
In this article, I am going to discuss the LINQ Select Projection 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 related to Linq Select Projection Operator in C#.
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 classes 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.
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 Employee IDs only using both method and query syntax.

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.
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 project the First Name, Last Name, and Salary
properties to the above newly created EmployeeBasicInfo class.

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

Difference between Select and SelectMany in LINQ

Select and SelectMany are projection operators. A select


operator is used to select value from a collection and
SelectMany operator is used to selecting values from a
collection of collection i.e. nested collection.
Select operator produces one result value for every source
value while SelectMany produces a single result that
contains a concatenated value for every source value.
Actually, SelectMany operator flatten
IEnumerable<IEnumerable<T>> to IEnumrable<T> i.e. list
of list to list.
class Employee
{

public string Name { get; set; }

public List<string> Skills { get; set; }

class Program

static void Main(string[] args)

List<Employee> employees = new List<Employee>();

Employee emp1 = new Employee { Name = "Deepak", Skills


= new List<string> { "C", "C++", "Java" } };

Employee emp2 = new Employee { Name = "Karan", Skills


= new List<string> { "SQL Server", "C#", "ASP.NET" } };

Employee emp3 = new Employee { Name = "Lalit", Skills


= new List<string> { "C#", "ASP.NET MVC", "Windows
Azure", "SQL Server" } };

employees.Add(emp1);

employees.Add(emp2);

employees.Add(emp3);
// Query using Select()

IEnumerable<List<String>> resultSelect =
employees.Select(e=> e.Skills);

Console.WriteLine("**************** Select
******************");

// Two foreach loops are required to


iterate through the results
// because the query returns a collection
of arrays.
foreach (List<String> skillList in
resultSelect)
{
foreach (string skill in skillList)
{
Console.WriteLine(skill);
}
Console.WriteLine();
}
// Query using SelectMany()
IEnumerable<string> resultSelectMany =
employees.SelectMany(emp => emp.Skills);

Console.WriteLine("****************
SelectMany ******************");

// Only one foreach loop is required to


iterate through the results
// since query returns a one-dimensional
collection.
foreach (string skill in resultSelectMany)
{

Console.WriteLine(skill);

Console.ReadKey();

/* Output
**************** Select ******************

C++

Java

SQL Server

C#

ASP.NET

C#

ASP.NET MVC

Windows Azure

SQL Server

**************** SelectMany ******************

C++

Java

SQL Server

C#

ASP.NET
C#

Understanding Single, SingleOrDefault,


First and FirstOrDefault
LINQ provides element operators which return a single element or a specific
element from a collection. The elements operators are Single,
SingleOrDefault, First, FirstOrDefault, Last, LastOrDefault.

Single
It returns a single specific element from a collection of elements if element
match found. An exception is thrown, if none or more than one match found
for that element in the collection.

SingleOrDefault
It returns a single specific element from a collection of elements if element
match found. An exception is thrown, if more than one match found
for that element in the collection. A default value is returned, if no
match is found for that element in the collection.
List<int> data = new List<int> { 10, 20, 30, 40, 50 };

//Try to get element at specified position

Console.WriteLine(data.ElementAt(1)); //result:20

//Try to get element at specified position if exist, else returns default


value

Console.WriteLine(data.ElementAtOrDefault(10)); //result:0, since default


value is 0

Console.WriteLine(data.First()); //result:10

Console.WriteLine(data.Last()); //result:50
//try to get first element from matching elements collection

Console.WriteLine(data.First(d => d <= 20)); //result:10

//try to get first element from matching elements collection else returns
default value

Console.WriteLine(data.SingleOrDefault(d => d >= 100)); //result:0, since


default value is 0

//Try to get single element

// data.Single(); //Exception:Sequence contains more than one element

//Try to get single element if exist otherwise returns default value

// data.SingleOrDefault(); //Exception:Sequence contains more than one


element

//try to get single element 10 if exist

Console.WriteLine(data.Single(d => d == 10)); //result:10

//try to get single element 100 if exist otherwise returns default value

Console.WriteLine(data.SingleOrDefault(d => d == 100)); //result:0, since


default value is 0

First
It returns first specific element from a collection of elements if one or more
than one match found for that element. An exception is thrown, if no match
is found for that element in the collection.

FirstOrDefault
It returns first specific element from a collection of elements if one or more
than one match found for that element. A default value is returned, if no
match is found for that element in the collection.

When to use Single, SingleOrDefault, First and


FirstOrDefault
You should take care of following points while choosing Single,
SingleOrDefault, First and FirstOrDefault:
1. When you want an exception to be thrown if the result set contains many
records, use Single or SingleOrDefault.
2. When you want a default value is returned if the result set contains no
record, use SingleOrDefault.
3. When you always want one record no matter what the result set
contains, use First or FirstOrDefault.
4. When you want a default value if the result set contains no record, use
FirstOrDefault.

Perfomance of SingleOrDefault and FirstOrDefault


FirstOrDefault usually perform faster as compared SingleOrDefault, since
these iterate the collection until they find the first match. While
SingleOrDefault iterate the whole collection to find one single match.
*/

You might also like