简体   繁体   中英

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

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

<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. Then you could quickly dump out the results.

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

You can also use "Aggregate" function provided with LINQ.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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