Search code examples
c#listtitle-case

Convert elements in a List to Title-Case?


I am trying to convert all list items to TitleCase. I thought TitleCase would be simple, but it does not seem to work the same as uppercase or lowercase. Any ideas? This is what works for upper and lower:

List myList = new List() { "abc", "DEF", "Def", "aBC" };

myList = myList.ConvertAll(x => x.ToUpper());
myList = myList.ConvertAll(x => x.ToLower());

but neither of these work:

myList = myList.ConvertAll(x => x.ToTitleCase());
myList = myList.ConvertAll(x => x.TitleCase());

Solution

  • Use TextInfo.ToTitleCase method.

    List<string> myList = new List<string>() { "abc", "DEF", "Def", "aBC" };
    CultureInfo currentCulture =  System.Threading.Thread.CurrentThread.CurrentCulture;
    myList = myList.Select(r=> currentCulture.TextInfo.ToTitleCase(r.ToLower())).ToList();
    

    output:

    foreach (string str in myList)
        Console.WriteLine(str);
    

    Result:

    Abc
    Def
    Def
    Abc
    

    EDIT:

    You can use ConvetAll like:

    myList =  myList.ConvertAll(r => currentCulture.TextInfo.ToTitleCase(r.ToLower()));