Tom Cruise
Tom Cruise

Reputation: 1415

Linq Reverse string c#

I want to reverse a string as given in the example.

 string[] actor = new string[] { "amitabh", "abhishek", "jitendra", "Salman", "Aishwariya" };

 var  resultstring= actor.Reverse().Select(c => c.Reverse()).ToArray();

    foreach(var m in resultstring)
    {
     //how to fetch this?
    }

the output should be

ayirawhsia,namlas,ardnetij,kehsihba,hbatima

Most of the post mentioned on how to reverse without using built in reverse().

I need the result using only reverse built in function using linq. I am able to make it as shown in the above snippet but couldnt reach the end.

Can someone help me to fix this?

Upvotes: 3

Views: 17641

Answers (3)

Antonín Lejsek
Antonín Lejsek

Reputation: 6103

If the output is the only thing desired, this is enough

Console.WriteLine(string.Join(",", actor).Reverse().ToArray());

Upvotes: 2

Orel Eraki
Orel Eraki

Reputation: 12196

In order to accomplish that i've broke it down into:

  1. Enumerate on every cell.
  2. Reverse the current string
  3. Converted it into char array.
  4. And the overloaded string constructor which accept char array.
  5. Iterate and print every string.

Code:

var actor = new[] { "amitabh", "abhishek", "jitendra", "Salman", "Aishwariya" };

var resultstring = actor.Reverse().Select(c => new string(c.Reverse().ToArray()));
foreach (var m in resultstring)
{
    Console.WriteLine(m);
}

Upvotes: 1

test
test

Reputation: 2639

Change this line:

var resultstring = actor.Reverse().Select(c => c.Reverse()).ToArray();

To this:

var resultstring = actor.Reverse().Select(c => new string(c.Reverse().ToArray())).ToArray();

Of note here is the fact that when you called Reverse on the string it actually returned an IEnumerable<char> when you were probably expecting a string. No problem, the string constructor accepts an array of char which is what my tweak to your code does.

Upvotes: 8

Related Questions