繁体   English   中英

创建 az 酒吧

[英]creating a-z bar

下面是我目前正在使用的代码,但想知道有没有更好的方法来做我正在做的事情......我正在创建 az model,例如 AB C D E....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
}

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

// 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的列表,output 将是

<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>

您可以使用 Linq GroupBy 并按首字母对所有名称进行分组。 然后,您可以快速转储结果。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM