简体   繁体   English

创建 az 酒吧

[英]creating a-z bar

below is the code i am using currently but wondering is there a better way of doing what i am doing... i am creating az model like AB C D E....Z下面是我目前正在使用的代码,但想知道有没有更好的方法来做我正在做的事情......我正在创建 az model,例如 AB C D E....Z

any thoughts?有什么想法吗?

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
}

It looks like you are going using the collection's enumerator directly and hardcoding specific code for each letter.看起来您将直接使用集合的枚举器并为每个字母硬编码特定代码。 Presumably, output should be the same for each letter, with the only difference being the letter itself.据推测,每个字母的 output 应该相同,唯一的区别是字母本身。 I would scrap your current code and instead do something like the following.我会废弃您当前的代码,而是执行以下操作。

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

For a list containing the names Alpha, Charlie, Delta, Alpha, Bravo , the output will be对于包含名称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>

You could use Linq GroupBy and group all of the names by the first letters.您可以使用 Linq GroupBy 并按首字母对所有名称进行分组。 Then you could quickly dump out the results.然后,您可以快速转储结果。

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

You can also use "Aggregate" function provided with LINQ.您还可以使用 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