Use LINQ and lambdas to put string in proper case
- by Tobias Funke
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?