Question

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());
Was it helpful?

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()));

OTHER TIPS

 class Program
    {
        static void Main(string[] args)
        {

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

            CultureInfo currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
            myList=myList.ConvertAll(r => currentCulture.TextInfo.ToTitleCase(r.ToLower()));
            int i=0;
            myList.ForEach(delegate(string k)
            {
                 Console.WriteLine(k);
                 i++;
            });
            Console.ReadLine();
        }
    }

Yes, if original values are uppercase, you have to drop to lower. You may also need to add Globalization namespace. I used this in a DropDownList_DataBound event.

CultureInfo currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture;        
foreach (ListItem li in DropDownList.Items)
{
     li.Text = currentCulture.TextInfo.ToTitleCase(li.Text.ToLower());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top