Home > Enterprise >  Why are my reverse and skip methods not working and why can't I assign a variable to this new a
Why are my reverse and skip methods not working and why can't I assign a variable to this new a

Time:12-17

I have an algorithm challenge that I have to solve which requires me to reverse an input string and take only the elements of the array after the element in index 1.

using System.Linq;

Console.WriteLine("Please enter a string");
string input = Console.ReadLine();

char[] inputArr = input.ToCharArray();
inputArr.Reverse().Skip(2);
Console.WriteLine(inputArr);

Basically, the inputArr when printed is exactly the same as the original string. Why is this so?

Also, when I try to assign, for example:

char[] reversedArr = inputArr.Reverse();

I get thrown an error saying I cannot implicitly convert type System.Collections.Generic.IEnumerable<char> to 'char[]'. I don't really understand this.

CodePudding user response:

It seems counterintuitive, but you need to declare a new variable when you reverse it.

Change code to:

char[] inputArr = input.ToCharArray();
var reversed = inputArr.Reverse();
Console.WriteLine(reversed.Skip(2));

This should sidestep the exception you were getting because it implicitly declares the reversed variable so type conversion shouldn't be an issue.

CodePudding user response:

You are using the Linq .Reverse method. All linq methods return new values or enumerables, leaving the original collection untouched. All linq methods work on IEnumerable, but in some cases there is some overlap between methods on the actual collection type. For example List.Sort vs Linq .OrderBy, the first sorts in place, the second returns a new collection.

If you want to reverse the collection in place there is Array.Reverse. The in place equivalent to Skip would be to use a 'span', i.e.

var mySpan = inputArr.AsSpan().Slice(2)

Code using Linq is usually easier to read and reason about. Code using spans and in place modification tend to be faster, but this is usually only relevant when working on very large sets of data.

CodePudding user response:

There are static Array.Reverse methods that reverse the array in-place.

However you are using the LINQ Reverse and Skip methods that leave the input unchanged and return a new enumerable (which you ignore).

So you will need to catch that returned value. However, the returned value has a type of Enumerable<char>, so you will need to create an array of that by using ToArray:

char[] reversed =  inputArr.Reverse().Skip(2).ToArray();

and convert that to a string

Console.WriteLine(new string(reversed));
  •  Tags:  
  • c#
  • Related