创建a-z栏

时间:2011-06-03 20:28:41

标签: c# asp.net

下面是我目前正在使用的代码,但想知道是否有更好的方法来做我正在做的事情...我正在创建像A B C D E ...... Z

的a-z模型

有什么想法吗?

if (myEnum.MoveNext())
{
     MyNames t = myEnum.Current;

    if (t.Name.ToLower().StartsWith("a"))
    {
        if (_a == 0)
        {
            l = new Literal();
            //.....
            _a = 1;
        }
    }
    if (t.Name.ToLower().StartsWith("b"))
    {
        if (_b == 0)
        { 
            l = new Literal();
            l.Text = "<h1 id='B'><span>B</span></h1>" + Environment.NewLine;
            _b = 1;
        }
    }
   .....c..d...e...f...g....z
}

3 个答案:

答案 0 :(得分:3)

看起来你正在直接使用该集合的枚举器并为每个字母硬编码特定代码。据推测,每个字母的输出应该相同,唯一的区别是字母本身。我会废弃您当前的代码,而是执行以下操作。

// note: replace yourList with the correct collection variable
var distinctLetters = 
    yourList.Select(item => item.Name.Substring(0,1).ToUpper())
            .Distinct()
            .OrderBy(s => s);

StringBuilder builder = new StringBuilder();
foreach (string letter in distinctLetters)
{
    // build your output by Appending to the StringBuilder instance 
    string text = string.Format("<h1 id='{0}'><span>{0}</span></h1>" + Environment.NewLine, letter);
    builder.Append(text);
}

string output = builder.ToString(); // use output as you see fit

对于包含名称Alpha, Charlie, Delta, Alpha, Bravo的列表,输出将为

<h1 id='A'><span>A</span></h1>
<h1 id='B'><span>B</span></h1>
<h1 id='C'><span>C</span></h1>
<h1 id='D'><span>D</span></h1>

答案 1 :(得分:2)

您可以使用Linq GroupBy并按首字母分组所有名称。然后你可以快速转出结果。

http://msdn.microsoft.com/en-us/vcsharp/aa336754.aspx#simple2

答案 2 :(得分:1)

您还可以使用LINQ提供的“聚合”功能。

string[] list = { "a", "b", "c" };

var output = list.Aggregate("", (current, listitem) => current + (Environment.NewLine + "<h1 id='" + listitem.ToUpper() + "'><span>" + listitem.ToUpper() + "</span></h1>"));