Thursday, January 21, 2010

LINQ extension method to Capitalize string

LINQ extension method to Capitalize first letter of each word in a sentence:

public static string Capitalize(this string s)
{
    return s.ToCharArray().Aggregate(String.Empty,
      (currentWord, nextWord) =>
        currentWord.Length == 0 && nextWord != ' ' ? nextWord.ToString().ToUpper() : (
          currentWord.EndsWith(" ") ? currentWord + nextWord.ToString().ToUpper() :
            currentWord + nextWord.ToString()
      )
    );
}

1 comment:

Pieter said...

Thanks! Works great!