Willy David Jr
Willy David Jr

Reputation: 9151

How to Reverse All Strings in String Array using LINQ?

I have a lot of strings in my string array. I want to reverse it via LINQ. Although I can do it using a for loop using Array.Reverse, I wonder if I can do it using LINQ?

This is my code but its not working as expected:

string[] strTemp = new string[] {"Hello", "World", "Foo"};
string[] strResult = strTemp.Select((a, b) => new { Value = a, Index = b })
                   .Select(y => y.Value.ToCharArray().Reverse().ToString()).ToArray();

My expected result should be:

"olleH", "dlroW", "ooF"

Upvotes: 1

Views: 824

Answers (2)

Antonín Lejsek
Antonín Lejsek

Reputation: 6103

string[] strResult = strTemp.Select(y => string.Concat(y.Reverse())).ToArray();

Upvotes: 3

Nieminen
Nieminen

Reputation: 1284

It sounds like you're trying to reverse the individual strings in the array, and not reverse the order of the elements, is that correct? If so, try this.

string[] strResult = strTemp.Select(s => Array.Reverse(s.ToCharArray()).ToString()).ToArray();

I don't have access to my c# machine, so I can't test this.

Upvotes: 0

Related Questions