0

The error is

The best overloaded method match for 'string.String(char[])' has some invalid arguments

My code:

string reverseValue = new string(
                      value.Select((c, index) => new { c, index })
                      .OrderByDescending(x => x.index).ToArray());
LarsTech
  • 80,625
  • 14
  • 153
  • 225

4 Answers4

4
char[] chars = value.ToCharArray();
Array.Reverse(chars);
new String(chars);

Or (somewhat slower)

new String(value.Reverse().ToArray());

Note that this won't handle UTF32 surrogate pairs, nor combining characters.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

You're selecting a new object, not chars. Try this:

string reverseValue = new string( 
                            value.Select((c, idx) => new { 
                                                       charVal = c,  
                                                       index = idx 
                                                     })
                                 .OrderByDescending(x => x.index)
                                 .Select(x => x.charVal)
                                 .ToArray());

Assuming this is more than academic, might I suggest:

/// <summary>
/// Reverses a string
/// </summary>
public static string ReverseString(this string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}

Usage:

string reverseValue = value.ReverseString();
Jaime Torres
  • 10,365
  • 1
  • 48
  • 56
1

You forgot to select the characters:

string reverseValue = new string(
    value.Select((c, index) => new { c, index })
    .OrderByDescending(x => x.index)
    .Select(x => x.c)
    .ToArray()
); 

Also notice that this is hugely inefficient method to reverse a string. You could use Array.Reverse or if you really care about performance:

public static string Reverse(string input)
{
    var length = input.Length;
    var last = length - 1;
    var chars = input.ToCharArray();
    for (int i = 0; i < length / 2; i++)
    {
        var c = chars[i];
        chars[i] = chars[last - i];
        chars[last - i] = c;
    }
    return new string(chars);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

Why wouldn't you just do something like:

    string r = new string( s.Reverse().ToArray() ) ;

or (since Reverse() is already taken) something like this:

public static class StringHelpers
{
    public static string ToReverse( this string s )
    {
        char[] buf = new char[s.Length] ;
        int    i   = 0        ; 
        int    j   = s.Length ;
        while ( j > 0 )
        {
            buf[i++] = s[--j] ;
        }
        return new string(buf) ;           
    }

}

it's not LINQ, but I'm willing to bet it performs better than LINQ in this situation.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135