Here’s a simple problem. I have an application that takes a phone number like ‘13335557777’, and needs to reverse it and insert a dot between each number, like this:
‘7.7.7.7.5.5.5.3.3.3.1.’
I know I can do this with a StringBuilder and a for-loop to reverse the string and insert the dots, but is there a clever way to do this in LINQ (or some other way)?
Note: for this, I’m not really concerned with performance or memory allocation or whatever, just curious to see how this would be done in LINQ.
Try this
EDIT
This solution is definitely aimed at the ‘clever’ end. It’s likely much more performant to use a StringBuilder to build up the string. This solution creates many intermediate strings.
EDIT2
There was some debate about the relative speed of the ‘clever’ solution vs. the StringBuilder approach. I wrote up a quick benchmark to measure the approach. As expected, StringBuilder is faster.
However, whether or not the speed difference is signficant is highly dependent upon where it is actually used in your application.
Code for the benchmark.