将List中的元素转换为Title-Case?

时间:2012-12-18 06:47:05

标签: c# list title-case

我正在尝试将所有列表项转换为TitleCase。我认为TitleCase很简单,但它似乎与大写或小写不一样。有任何想法吗?这适用于上层和下层:

列出myList = new List(){“abc”,“DEF”,“Def”,“aBC”};

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

但这些都不起作用:

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

3 个答案:

答案 0 :(得分:5)

使用TextInfo.ToTitleCase方法。

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

输出:

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

结果:

Abc
Def
Def
Abc

编辑:

您可以使用ConvetAll:

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

是的,如果原始值是大写,则必须降低到更低。您可能还需要添加Globalization命名空间。我在DropDownList_DataBound事件中使用了它。

CultureInfo currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture;        
foreach (ListItem li in DropDownList.Items)
{
     li.Text = currentCulture.TextInfo.ToTitleCase(li.Text.ToLower());
}