Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Lambda, LINQ .... improve this method

Tags:

c#

lambda

linq

I am in the process of learning more about LINQ and Lambda expressions but at this stage, I simply don't "Get" Lambda expressions.

Yes ... I am a newbie to these new concepts.

I mean, every example I see illustrates how to add or subtract to parameters.

What about something a little more complex?

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).

i.e.
"SampleText" = "Sample Text"
"DoesNotMatterHowManyWords" = "Does Not Matter How Many Words"

Here is the code;

public static string ProperSpace(string text)
{
    var sb = new StringBuilder();
    var lowered = text.ToLower();

    for (var i = 0; i < 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();
}

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.

Also, if you have any good links to LINQ or Lambda tutorials, please provide.


EDIT

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.

Here is the newly updated method using a Lambda expression (tested to work);

public static string ProperSpace(string text)
{
    return text.Aggregate(new StringBuilder(), (sb, c) =>
    {
        if (Char.IsUpper(c)) sb.Append(" ");
        sb.Append(c);
        return sb;
    }).ToString().Trim();
}

I also appreciate the many links to other (similar) topics.

In particular this topic which is so true.

like image 739
Fleming Avatar asked Mar 27 '09 12:03

Fleming


1 Answers

This is doing the same as the original code and even avoids the generation of the second (lower case) string.

var result = text.Aggregate(new StringBuilder(), 
    (sb, c) => (Char.IsUpper(c) ? sb.Append(' ') : sb).Append(c));
like image 58
MartinStettner Avatar answered Sep 21 '22 23:09

MartinStettner