Trying to reverse a string but getting error in Aggregate function
private string Reverse(string strValue)
{
char[] chArray = strValue.ToCharArray();
var reverse = chArray.Reverse();
var res = reverse.Aggregate((a,b)=>a+b);
return res.ToString();
}
Cannot implicitly convert type ‘int’ to ‘char’. An explicit conversion exists (are you missing a cast?)
So what is the mistake?
Exactly as it says: the result of
a + bis anint, but you want it to be achar. To get it to compile you can just use:… but I don’t think that will do what you want it to.
I suggest you don’t use LINQ for this to start with:
Note that this doesn’t work properly with things like combining characters, surrogate pairs etc.
If you really wanted to use LINQ, you could do it with:
There’s no need to call
Aggregate. If you really want to make it slow and use string concatenation withAggregate(it’ll be O(n2)) you can do it like this:Here’s we’ve provided a string seed value, so the parameter
strwill be a string and+will be string concatenation, not character addition.You can make it more efficient using
StringBuilder:… but I’m still not sure it’s worth it…