(C# Language) LINQ - Select, Where, OrderBy and OrderByDescending

In this tutorial we learn the use of Select, Where, OrderBy and OrderByDescending functions provided by C# LINQ. A program has been used to explain these functions. This will help you get started but experience is the best teacher. So all I can help you is get started.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

Create a Project

Create a C# console project for the latest version of .NET Core. Open the solution explorer and add a file called Population.cs. This file contains the definition for a record class that contains two properties - CityCode and Size.


// population.cs file 

record class Population(String CityCode, Int32 Size);

We shall use items of this type for studying this tutorial.

Video Explanation (see it happen!)

Please watch the following youtube video:

Select Query

We shall start by studying a Select query on a collection.

Open the solution explorer, and the program.cs file. Let's write our code for a select query.

First we create a list of Population items.

The concept of a Select in LINQ is the same as SELECT statements in SQL. A select query is used for returning a subset of the columns of the items of a collection. For example, we can use a select query to return only the city codes.

C# LINQ provides built-in method for executing a select LINQ query. This method can be used on any IEnumerable list or array.

We can check the intellisense options on the population list. We observe that the select method is available.

So let us apply the Select method.



using ConsoleApp1;

List<Population> ls = new() {
                                new("ACD", 2310),
                                new("BRT", 2000),
                                new("CED", 500),
                                new("QCM", 1030)
                            };

// creates a query for codes 
// but doesn't execute it 
var onlyCodes = ls.Select (item => new { Code = item.CityCode })
                  .Where (c => c.Code[0] < 'M')
                  .OrderBy(p => p.Code[1]);

// execution done here  
foreach(var k in onlyCodes)
{
  Console.WriteLine(k.Code);
}

  

This method accepts a Func delegate as an argument. A lambda expression can be used to specify for this purpose.

We have used item goes to an anonymous. The select method calls this delegate on each item of the list and returns an anonymous that contains a property called Code.

It is important to note that LINQ functions use yield statements for optimization. This is called lazy execution. The query doesn't execute till the results are extracted through a loop or through a function such as ToList and ToArray. These functions make calls to the yield statements and stream out the results in an optimal way.

Lastly, we have used a for-each loop to display the results of this query. We verify that only the codes are displayed.

Where in LINQ

Now let's see the use of Where.

We can use the Where function for filtering records. Where function accepts a delegate that returns true or false.

A lambda expression is used to specify the filter conditions. For example we can append a Where to the Select to take only those records with codes that start with a character prior to "M". We have used dot Where c goes to c.Code[0] < 'M'.

  
// Where filter 
var onlyCodes = ls.Select (item => new { Code = item.CityCode })
                .Where (c => c.Code[0] < 'M')
  
  

Now we can again run the code. We observe that the code QCM is missing now.

OrderBy in LINQ

Next let's see the use of OrderBy.

An OrderBy is used for ordering the records in an ascending order.

We can chain an OrderBy to the Where to specify the orderby selector.

We have written dot OrderBy p goes to the second char of the Code.


// OrderBy 

var onlyCodes = ls.Select (item => new { Code = item.CityCode })
                  .Where (c => c.Code[0] < 'M')
                  .OrderBy(p => p.Code[1]);  
  
  

We can again the run the project to verify that the records are ordered as ACD, CED and BRT because we specified that the ordering be on the second character of Code.

Ordering can be done in descending order by using the OrderByDescending function in the same way.

Ordering can be done on multiple columns by using the ThenBy functions.

The source code has been attached to the downloads of this tutorial. Thankyou.


This Blog Post/Article "(C# Language) LINQ - Select, Where, OrderBy and OrderByDescending" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.