Home > Net >  Reverse a Span in NetStandard 2
Reverse a Span in NetStandard 2

Time:10-29

I need to reverse a Span<Char>, and it would be easy if I were using NetStandard 2.1.

I could use MemoryExtensions.Reverse(Span), but unfortunately, it's not supported in the version I am using.

I tried to copy the code from the repository, but it uses some language features that don't exist in the NetStandard 2.0.

I don't mind using a less optimized implementation because it's not often used in my code. Still, I cannot convert it to string and then reverse it because I cannot handle garbage collection triggers in this implementation.

How to reverse a Span<Char> without converting to string or upgrading the NetStandard version?

CodePudding user response:

Any reason why not a simple for loop, if being super efficient is not criticial?

Span<int> x = new[] { 1, 2, 3, 4 }.AsSpan();
for (int i = 0, j = x.Length - 1; i < j; i  , j--)
{
    var temp = x[i];
    x[i] = x[j];
    x[j] = temp;
}

CodePudding user response:

Install latest System.Memory NuGet package, and MemoryExtensions.Reverse method will be available for you to use.

  • Related