Use LINQ and lambdas to put string in proper case

Posted by Tobias Funke on Stack Overflow See other posts from Stack Overflow or by Tobias Funke
Published on 2010-04-09T20:43:53Z Indexed on 2010/04/09 21:13 UTC
Read the original article Hit count: 345

Filed under:
|
|

I have this function called ProperCase that takes a string, then converts the first letter in each word to uppercase. So ProperCase("john smith") will return "John Smith". Here is the code:

    public string ProperCase(string input)
    {
        var retVal = string.Empty;
        var words = input.Split(' ');

        foreach (var word in words)
        {
            if (word.Length == 1)
            {
                retVal += word.ToUpper();
            }
            else if (word.Length > 1)
            {
                retVal += word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower();
            }

            retVal += ' ';
        }

        if (retVal.Length > 0)
        {
            retVal = retVal.Substring(0, retVal.Length - 1);
        }

        return retVal;
    }

This code workds perfectly, but I'm pretty sure I can do it more elegantly with LINQ and lambdas. Can some please show me how?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ