Not that I would want to use this practically (for many reasons) but out of strict curiousity I would like to know if there is a way to reverse order a string using LINQ and/or LAMBDA expressions in one line of code, without utilising any framework "Reverse" methods.
e.g.
string value = "reverse me";
string reversedValue = (....);
and reversedValue will result in "em esrever"
EDIT Clearly an impractical problem/solution I know this, so don't worry it's strictly a curiosity question around the LINQ/LAMBDA construct.
You can use
Aggregate
to prepend eachChar
to the reversed string:Quite simple. So, from this point on, I have a single method that reverses a string, that doesn't use any built-in Reverse functions.
So in your main method, just go,
Console.WriteLine(Reverse("Some word"));
Technically that's your one liner :P
Variant with recursive lambda:
LP, Dejan
Well, I can do it in one very long line, even without using LINQ or a lambda:
(Dear potential editors: do not unwrap this onto multiple lines. The whole point is that it's a single line, as per the sentence above it and the question.)
However, if I saw anyone avoiding using framework methods for the sake of it, I'd question their sanity.
Note that this doesn't use LINQ at all. A LINQ answer would be:
Avoiding using Reverse, but using OrderByDescending instead:
Blech. I like Mehrdad's answer though. Of course, all of these are far less efficient than the straightforward approach.
Oh, and they're all wrong, too. Reversing a string is more complex than reversing the order of the code points. Consider combining characters, surrogate pairs etc...
I don't see a practical use for this but just for the sake of fun: