Note that there are some explanatory texts on larger screens.

plurals
  1. POc# Lambda, LINQ .... improve this method
    primarykey
    data
    text
    <p>I am in the process of learning more about LINQ and Lambda expressions but at this stage, I simply don't "Get" Lambda expressions. </p> <p>Yes ... I am a newbie to these new concepts.</p> <p>I mean, every example I see illustrates how to add or subtract to parameters. </p> <p>What about something a little more complex?</p> <p>To help me gain a better understanding I have posted a small challenge for anyone who wishes to participate. I have the following method which will take any string and will put spaces in between any upper case characters and their preceding neighbour (as shown below).</p> <p>i.e.<br> "SampleText" = "Sample Text"<br> "DoesNotMatterHowManyWords" = "Does Not Matter How Many Words"</p> <p>Here is the code;</p> <pre><code>public static string ProperSpace(string text) { var sb = new StringBuilder(); var lowered = text.ToLower(); for (var i = 0; i &lt; text.Length; i++) { var a = text.Substring(i, 1); var b = lowered.Substring(i, 1); if (a != b) sb.Append(" "); sb.Append(a); } return sb.ToString().Trim(); } </code></pre> <p>I am sure that the method above can be re-written to use with LINQ or a Lambda expression. I am hoping that this exercise will help open my eyes to these new concepts.</p> <p>Also, if you have any good links to LINQ or Lambda tutorials, please provide.</p> <hr> <p>EDIT</p> <p>Thanks to everyone who has contributed. Although the current method does do the job, I am happy to see it can be modified to utilize a lambda expression. I also acknowledge that this is perhaps not the best example for LINQ.</p> <p>Here is the newly updated method using a Lambda expression (tested to work);</p> <pre><code>public static string ProperSpace(string text) { return text.Aggregate(new StringBuilder(), (sb, c) =&gt; { if (Char.IsUpper(c)) sb.Append(" "); sb.Append(c); return sb; }).ToString().Trim(); } </code></pre> <p>I also appreciate the many links to other (similar) topics.</p> <p>In particular <a href="https://stackoverflow.com/questions/689569/overcomplication-to-use-the-latest-features">this topic</a> which is so true. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload