Seeking in arrays using the Range and the Index operator in C# >= 8

Seeking in arrays using the Range and the Index operator in C# >= 8

I just used the Range operator (C# 8 feature) instead of the Spoony loop I used to do :)) Why I did not know this before, Shame on me!!! -_-

I was like "Maybe same as me, a few of them ( My connections on Linkedin which developing using C# language :p ) do not know about this pretty concept as well. Then instead of sharing some political dirt or creating a QA about Guess what my grandmother's favorite color is? I decided to create this short article here :P

So let`s get started with an example:

static string[] GetFirstFiveOfArray(string[] array)
{

  var firstFive = new string[5];

  for (int i = 0; i < 5; i++)
  {
    firstFive[i] = array[i];
  }

  return firstFive;
}


var alphabet = new string[] { "A", "B", "C", "D", "E", "F" };

var firstFive = GetFirstFiveofArray(alphabet);

By using this new feature you are going to have something like the below :D

var alphabet = new string[] { "A", "B", "C", "D", "E", "F" };


var firstFive = alphabet[..5];

Is it sounds great? So be happy we have more than this tiny stuff here :D

It has introduced a "^" operator that let us get the last element in the sequence like this:

var lastTwo = alphabet[^2..];

It has also exposed two types "Range" and "Index" which are responsible to keep the new array navigation operator in themselves for an example:

Range lastTwoRange = ^2..;

var lastTwo = alphabet[lastTwoRange];

//And the Index 

Index lastIndex = ^1;

var lastIndex = alphabet[lastIndex];

Keep it up and take care of your updates :D

Seyed Zia Azimi

Team Lead | Software Developer at TOSAN (Banking and Payment Solutions Provider)

3 年

Instead of loop we can also use Linq operators. var alphabet = new string[]{"A", "B", "C", "D", "E", "F"}; var firstFive = alphabet.Take(5); By the way thanks for sharing ??

要查看或添加评论,请登录

Mo Ravaei的更多文章

社区洞察

其他会员也浏览了