Range and Reverse: New LINQ extensions in .NET 6

Maytham Fahmi
2 min readDec 24, 2021

--

Since .NET 6 is released recently, it is a good opportunity to mention some of the new LINQ extensions methods. I will post a series of small articles focused on some these new or maybe less known LINQ methods.

In this article I am going to take some examples of others new Linq features with some examples so it is easier to understand it.

Prerequisites

To to use these new LINQ extensions you need to download and install this version of .NET 6.

I download and install Visual Studio 2022 in this article.

Before we start with examples, lets create a simple list of strings:

var data = new[] { "person1", "person2", "person3", "person4", "person5" };

Now, lets start with some examples

Example, Take Reverse ElementAt

Normally if we need to take element at index 2 that contains person3 we write:

var getPerson3 = data.ElementAt(2); // forward take and count from index 0Output
person3

Now lets imagine we need to pick element at index 3 that contains person4 reverse wise:

var getPerson4 = data.ElementAt(^2); // revers take the second reversOutput
person4

Example, Skip and Take

Normally if we need to skip 2 elements and take 2 elements, we do write following code:

var get2PersonsAfterPerson2 = data.Skip(2).Take(2);Output 
person3 person4

Now with .net 6, it is possible to write, a short version of the above code:

var get2PersonsAfterPerson2New = data.Take(2..4);Output 
person3 person4

Now if we need to take 3 elements reverse wise we can write:

var get3PersonsReversFromPerson5 = data.Take(^3..);Output
person3 person4 person5

Download my examples form GitHub.

Originally published at https://itbackyard.com on December 24, 2021.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Maytham Fahmi
Maytham Fahmi

Written by Maytham Fahmi

Maytham is a passionate software developer with more than ten years of experience. His motivation is to help transform ideas into production ready systems.

No responses yet

Write a response