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