LINQ stands for Language-Integrated Query, a partial language that utilizes C# pass by reference in order to pass reference-type parameters as an argument to the method. 

It describes the integration technologies of querying into C# to convert a data source into query expressions. This is translated into a declarative query syntax to help developers organize and group together operations with a lot less code writing. 

Rather than having to pick up multiple query languages from SQL to XML, LINQ reads queries on the same level as classes, methods, and events.

Code on computer screen

What you need to know about LINQ query expressions

LINQ expressions are compiled into Standard Query Operator calls for C#, in which queries are parsed using either query or method syntax. The former is easier to read than the latter despite a lack of performance difference between them. 

Complete C# Masterclass

Last Updated May 2022

  • 282 lectures
  • All Levels
4.6 (19,566)

Learn C# Programming – WPF, Databases, Linq, Collections, Game Development with Unity. More than just the C# basics! | By Denis Panjuta, Tutorials.eu by Denis Panjuta

Explore Course

Upon encountering a source sequence, a query is likely to do the following things:

A LINQ query can be written in three ways: in query syntax, method syntax, or a mixture of both. Each query is made up of three components: initialization of the source, sorting of conditions, and selection of items by groups. 

This article will discuss LINQ operators in C#, outlined as a set of extension methods for structuring the queries. One of these is the LINQ Select operator. 

How to Implement LINQ Select with a String Type Collection

The LINQ Select operator takes a collection of item inputs and performs a projection on them to produce an output containing the same number of items. The projection is determined by the lambda expression passed to the Select operator.

A simple example of the select clause in action is to multiply all the integers in an array by a number. Each integer is looped over and updated, forming a new array which is printed into the console. It is also possible to manipulate a list of string items using LINQ Select. 

This method is demonstrated in the upcoming code analysis shown below:

List<string> countries = new List<string> { "USA", "CANADA", "AUSTRALIA", "ENGLAND", "CHINA", "RUSSIA" };
IEnumerable<string> orderedcon = countries.Select((n, i) => i+"-" + n);
foreach (string country in orderedcon)
{
Console.WriteLine(country);
}
Console.ReadLine();

In the sample code, “countries” is instantiated with several names. A LINQ Select iterates through the items by counting their indexes in the format: “(n, i) => i+”-” + n” where n and i are the parameters. When the strings are printed, it should look like this:

0-USA
1-CANADA
2-AUSTRALIA
3-ENGLAND
4-CHINA
5-RUSSIA

Not only can the Select operator change all the strings to upper/lower case, it is also capable of measuring their length. Select sends the collection through IEnumerable<type> to modify their properties one line at a time. 

In addition, Select has the option to replace any substring from the list through the lambda expression. This is seen in the foreach var of string country in replacedcon:

List<string> countries = new List<string> { "USA", "CANADA", "AUSTRALIA", "ENGLAND", "CHINA", "RUSSIA" };
IEnumerable<string> replacedcon = countries.Select(n => n.Replace("US", "EA"));
foreach (string country in replacedcon)
{
Console.WriteLine(country);
}

Applying a LINQ Projection to Custom Type Objects

LINQ Select is able to operate on custom types by highlighting a portion of the object instance from the main method. For instance, suppose you had an object class called Person that accepts a name string, age integer, and a datetime DOB, you could create a collection of objects to resemble different profiles. 

Here are some examples:

class Person
{
public string name;
public int age;
public DateTime dob;
public Person(string name, int age, DateTime dob)
{
this.name = name;
this.age = age;
this.dob = dob;
}
}
Person p1 = new Person("Adam", 22, new DateTime(1992, 2, 5));
Person p2 = new Person("Tori", 19, new DateTime(1995, 10, 6));
Person p3 = new Person("James", 29, new DateTime(1985, 11, 2));
Person p4 = new Person("Sofi", 24, new DateTime(1990, 4, 10));
List<Person> personlist = new List<Person> { p1, p2, p3, p4 };

Notice how it only selects individual values assigned to each variable of the custom type class by running a foreach loop. That is because LINQ Select uses the lambda expression which limits its search just to the name of every item where it states personlist.Select(n => n.name). 

Last but not least is the Select operator’s ability to chain onto other operators. For  example, if you want to organize all the names in the custom type Person, you have to select them and choose to order by length. You would need to chain the Select clause after an OrderBy onto “personlist” with.OrderBy(n => n.name.Length).Select(n => n.name). 

The standard template for the Select method is as follows:

First, you have a string collection instantiated from a public class: 

IList<Student> studentList = new List<Student>() { 
new Student() { StudentID = 1, StudentName = "John", Age = 13 } ,
new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } 
};

Then, you declare a variable for the select operator to iterate through the list and format each result to meet a specific condition: 

var selectResult = from s in studentList
 select new { Name = "Mr. " + s.StudentName, Age = s.Age }; 		
The foreach var will go through the collection in selectResult and write them to the console: 
foreach (var item in selectResult)
Console.WriteLine("Student Name: {0}, Age: {1}", item.Name, item.Age);} 
}

To briefly recap, LINQ Select always outputs an IEnumerate collection of elements based on a transformation concept. What it does is shape the data to format how object instances are selected in C# depending on which values the user has to acquire. 

To learn more about the best practices for implementing LINQ Select, it is recommended that you explore one of the courses on C# programming, especially those covering topics in OOP. There are lessons available for people of all skill levels, from teaching the fundamentals to advanced C# masterclasses. 

Interested in tackling more challenging problems? Here are some projects with real-world applications to test your knowledge. 


Frequently Asked Questions

What is select in LINQ?

The select clause is a LINQ query expression that queries results by specifying the type of each returned element. In other words, select tells you what the results will be, whether it’s an object, a single member, or a subset of elements. If the select operator produces something besides the source object, the operation becomes a projection, which is particularly useful for manipulating data through LINQ queries. 

The LINQ Select operator acts similar to the one in SQL. It allows a user to decide which properties and exactly how many to retrieve from the select operator. Likewise, it enables them to perform calculations by parsing lists out of the data source. Select is one of two available projection methods to highlight existing data in C#. 

What is the difference between select and where in LINQ?

The where clause is another LINQ query that falls under the category of filtering operators. LINQ where fetches a smaller set of data to see if it satisfies a given condition. The where operator implements extension methods on IEnumerable<T>, predicating as function parameters. It should return a Boolean value depending on the user input. 

The main difference between select and where is that select returns a projection for all items in the source, while the where extension only recovers items that match the filter statement. Select always returns a consistent number of elements, but the where operator can return fewer elements by adding limiting filters. 

In short, select deals with transformation properties, and where is involved in filtering restrictions. It is apparent that select produces its own output by accepting an input of IEnumerable and transforming elements. However, where needs an IEnumerable and a predicate to generate an output. 

Is LINQ select lazy?

Yes, many developers consider LINQ a form of lazy evaluation. Not to be taken at face value, LINQ select signifies that only one source element is processed for each call to the iterable. This iterator could be a foreach var, custom class, or while loop. Its counterpart is the eager evaluation, where the first call is capable of returning the entire collection. 

In fact, the principles of LINQ are founded on “laziness,” as the query does as little work as possible unless you force it to create a list of the dataset. Even so, it still recognizes many types of enumerables to iterate over, including lists, arrays, dictionaries, trees, and more. 

All the data is extracted from SQL and stored into memory one line at a time. After the foreach loop executes, the database is practically queried in one go.

Page Last Updated: December 2021

Top courses in C#

Complete C# Unity Game Developer 3D
Ben Tristem, Rick Davidson, GameDev.tv Team, Gary Pettie
4.7 (33,882)
Bestseller
C#/.NET - 50 Essential Interview Questions (Junior Level)
Krystyna Ślusarczyk
4.9 (146)
Bestseller
Design Patterns in C# Made Simple
Zoran Horvat
4.8 (196)
C#/.NET - 50 Essential Interview Questions (Mid Level)
Krystyna Ślusarczyk
4.9 (24)
Highest Rated
C# Intermediate: Classes, Interfaces and OOP
Mosh Hamedani
4.5 (28,510)
Bestseller
Learn Parallel Programming with C# and .NET
Dmitri Nesteruk
4.4 (2,718)
Bestseller
Advanced Topics in C#
Dmitri Nesteruk
4.5 (224)
RPG Core Combat Creator: Learn Intermediate Unity C# Coding
Ben Tristem, Rick Davidson, Sam Pattuzzi, GameDev.tv Team
4.8 (9,787)

More C# Courses

C# students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo