Range and Reverse: New LINQ extensions series

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 0
Output
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 revers
Output
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.

Leave a Comment