Linq Reverse string c#
Solution 1
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.
Solution 2
If the output is the only thing desired, this is enough
Console.WriteLine(string.Join(",", actor).Reverse().ToArray());
Solution 3
In order to accomplish that i've broke it down into:
- Enumerate on every cell.
- Reverse the current string
- Converted it into char array.
- And the overloaded
string constructor
which acceptchar array
. - 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);
}
Tom Cruise
Updated on June 07, 2022Comments
-
Tom Cruise almost 2 years
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?
-
Kevin over 8 yearsAn explanation of why this works better than his would be very helpful here
-
Kevin over 8 yearsYour code output does not match his example output because in his sample he both reversed the names and reversed the order in which they come out, whereas yours only reverses each name and not the order. I don't know whether or not he actually cares about the reversal of order, but it would be worth finding out
-
test over 8 yearsThe OP also needs to reverse the order of the strings as well as the order of the characters in the string.
-
Tom Cruise over 8 yearsIt works. i missed *new string * . any difference between var resultstring = actor.Reverse().Select(c => new string(c.Reverse().ToArray())).ToArray(); and var resultstring = actor.Reverse().Select(c => new string(c.Reverse().ToArray())); for both the cases im able to fetch the records in the for loop.
-
test over 8 years@Ammu You can safely drop that last call to
ToArray
. I just put it because you did.